﻿using DevExpress.DashboardCommon;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LSQL;
using DevExpress.CodeParser;
using Shopfloormanagement;
using Mysqlx.Crud;
using DevExpress.DataAccess.Native.Data;
using DataTable = System.Data.DataTable;
using Shopfloormanagement.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;
using System.Data.SqlClient;
using static Mysqlx.Expect.Open.Types;
using static DevExpress.CodeParser.CodeStyle.Formatting.Rules.LineBreaks;
using Shopfloormanagement.Pre_Form;
using Shopfloormanagment.Forms;
using static System.Net.WebRequestMethods;
using DevExpress.XtraExport.Helpers;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraCharts.Designer.Native;
using DevExpress.XtraPrinting.Native.WebClientUIControl;
using MySqlX.XDevAPI;
using System.Net.Http;
using Newtonsoft.Json;
using DevExpress.XtraGrid;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Shopfloormanagement.Rootcause_v02;


namespace Shopfloormanagement
{
    public partial class DevMainForm : DevExpress.XtraEditors.XtraForm
    {
        public static int maxDepLv;
        public static DevMainForm instance = new DevMainForm();
        private int[] depArray;
        public DevMainForm()
        {
            instance = this;
            InitializeComponent();
        }

        #region 页眉按键
        public void btnOverview_Click(object sender, EventArgs e)
        {

            mainTab.SelectedTabPageIndex = 0;
            //回到主页
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }

            LoadDepartment(SystemInfo.readLevel, SystemInfo.readFactory, SystemInfo.readparentDep);

            Search_keyCalendar();
            SearchGoSee();
            SearchFeedback();
            LoadTOP3();
            publicFunc.SetColorByRelation();
            SetUpperSQDC();
            A3number = "0";


            LoadMeeting();
            LoadMeetingInOverview();
        }

        private void btnAttendance_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 1;
            LoadMeeting();
        }

        private void btnActionplan_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 2;
            //Search_ActionPlan(0);
            lbAPaction_Click(sender, e);
        }

        private void btnTopissue_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 3;
            LoadinTopissue();
            Search_Topissue();
        }

        private void btnFeedback_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 4;
            lbFBactive_Click(sender, e);
        }

        private void btnGOSEE_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 5;
            lbGSactive_Click(sender, e);
        }

        private void btnA3_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }

            mainTab.SelectedTabPageIndex = 12;

            rootcause.instance.FormBorderStyle = FormBorderStyle.None;
            rootcause.instance.TopLevel = false;
            plA3.Controls.Add(rootcause.instance);
            rootcause.instance.Show();

            rootcause.instance.lblOverdue_Click(sender, e);
            rootcause.instance.lblTotal_Click(sender, e);
            rootcause.instance.lblActive_Click(sender, e);
            //A3list.DoubleClick += A3list_DoubleClick;//实现双击进入项目功能-绑定
        }

        private void btnLPA_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 7;
            Form_LPA.frm.FormBorderStyle = FormBorderStyle.None;
            Form_LPA.frm.TopLevel = false;
            plLPA.Controls.Add(Form_LPA.frm);
            Form_LPA.frm.Show();
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 8;
        }

        private void btnDeviation_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            mainTab.SelectedTabPageIndex = 9;
            lbActive_Click(sender, e);
        }

        private void btnCIP_Click(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name == "Form_Department") // 你可以用 Name 来判断
                {
                    plMain.Controls.RemoveAt(0);
                }
            }
            CIPSFMView.instance.Close();
            mainTab.SelectedTabPageIndex = 10;
            CIPSFMView.instance = new CIPSFMView();
            CIPSFMView.instance.TopLevel = false;
            CIPSFMView.instance.FormBorderStyle = FormBorderStyle.None;
            plCIP.Controls.Add(CIPSFMView.instance);
            CIPSFMView.instance.Show();
        }

        #endregion

        private void DevMainForm_Load(object sender, EventArgs e)
        {
            picS.MenuManager = barManager2;
            barManager2.SetPopupContextMenu(picS, kpiPopMenu);

            picQ.MenuManager = barManager2;
            barManager2.SetPopupContextMenu(picQ, kpiPopMenu);

            picD.MenuManager = barManager2;
            barManager2.SetPopupContextMenu(picD, kpiPopMenu);

            picC.MenuManager = barManager2;
            barManager2.SetPopupContextMenu(picC, kpiPopMenu);

            maxDepLv = publicFunc.MaxDepartmentLevel();
            //使TabPage的页眉隐藏
            mainTab.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;

            //使Label居中
            lbTitle.Left = (plTitle.Width - lbTitle.Width) / 2;
            lbTitle.Top = (plTitle.Height - lbTitle.Height) / 2;

            //消息按键角标
            DataTable dt = publicFunc.UserIncompleteAction(SystemInfo.userID);
            badge.TargetElement = btnMessage;
            badge.Appearance.BackColor = Color.Red;
            badge.Appearance.ForeColor = Color.White;
            badge.Properties.Text = dt.Rows.Count.ToString();//需要修改成用户自己的数字
            badge.Properties.Location = ContentAlignment.TopRight;

            picS.MouseDown += ImageEdit_MouseDown;
            picQ.MouseDown += ImageEdit_MouseDown;
            picD.MouseDown += ImageEdit_MouseDown;
            picC.MouseDown += ImageEdit_MouseDown;

            //测试后删除
            //SystemInfo.readFactory = 7;
            //SystemInfo.readLevel = 3;
            //SystemInfo.readparentDep = 39;

            //部门快捷选择框加载数据
            LoadDepartment(SystemInfo.readLevel, SystemInfo.readFactory, SystemInfo.readparentDep);

            Search_keyCalendar();
            SearchGoSee();
            SearchFeedback();
            LoadTOP3();
            SetUpperSQDC();

            LoadMeeting();
            LoadMeetingInOverview();

            string currDep = "";
            if (SystemInfo.readparentDepName == "")
            {
                currDep = SystemInfo.readFactoryName;
            }
            else
            {
                currDep = SystemInfo.readparentDepName;
            }
            lbCurrDep.Text = $"Now browsing: {currDep}";

            btnScore.Visible = false; 
            btnScore.Enabled = false;
        }

        #region 主页 
        private List<PanelControl> panelControls;
        private List<LabelControl> labelControls;
        private List<PictureEdit> pictureEdits;

        //获取上方SQDC
        private PictureEdit currentPic = null;
        private void ImageEdit_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && sender is PictureEdit pic)
            {
                currentPic = sender as PictureEdit;

            }
        }
        private void popBtnSQDCrelation_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (currentPic != null)
            {
                string controlName = currentPic.Name;
                kpiRelation.FormText = controlName.Replace("pic", "");

                kpiRelation.instance.ShowDialog();
            }


        }

        public void LoadinOverview()
        {
            maxDepLv = publicFunc.MaxDepartmentLevel();
            //使TabPage的页眉隐藏
            mainTab.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;

            //使Label居中
            lbTitle.Left = (plTitle.Width - lbTitle.Width) / 2;
            lbTitle.Top = (plTitle.Height - lbTitle.Height) / 2;

            //消息按键角标
            DataTable dt = publicFunc.UserIncompleteAction(SystemInfo.userID);
            badge.TargetElement = btnMessage;
            badge.Appearance.BackColor = Color.Red;
            badge.Appearance.ForeColor = Color.White;
            badge.Properties.Text = dt.Rows.Count.ToString();//需要修改成用户自己的数字
            badge.Properties.Location = ContentAlignment.TopRight;

            //测试后删除
            //SystemInfo.readFactory = 7;
            //SystemInfo.readLevel = 3;
            //SystemInfo.readparentDep = 39;

            //部门快捷选择框加载数据
            LoadDepartment(SystemInfo.readLevel, SystemInfo.readFactory, SystemInfo.readparentDep);

            Search_keyCalendar();
            SearchGoSee();
            SearchFeedback();
            LoadTOP3();
            SetUpperSQDC();

            SqlDependency.Start(SystemInfo.SQL);

            string currDep = "";
            if (SystemInfo.readparentDepName == "")
            {
                currDep = SystemInfo.readFactoryName;
            }
            else
            {
                currDep = SystemInfo.readparentDepName;
            }
            lbCurrDep.Text = $"Now browsing: {currDep}";
        }

        private void UpdateUI(string[] dep, int[] depID)
        {
            int count = dep.Length;
            for (int i = 0; i < panelControls.Count; i++)
            {
                panelControls[i].Visible = false;
            }

            // 查询当前层级有多少部门，控制显示Panel的数量和内容
            for (int i = 0; i < count; i++)
            {
                labelControls[i].Text = dep[i];
                //使Label居中
                labelControls[i].Left = (panelControls[i].Width - labelControls[i].Width) / 2;


                Image image = GetImageFromResources(depID[i]);
                if (image != null)
                {
                    pictureEdits[i].Image = image;
                    pictureEdits[i].Properties.ShowMenu = false;
                }
                else
                {
                    pictureEdits[i].Image = Properties.Resources.defaultPic;
                    pictureEdits[i].Properties.ShowMenu = false;
                }
                panelControls[i].Visible = true;
                panelControls[i].Click += DepPanelClick;
                //此处应该有设置SQDC的逻辑
                SetSQDC(i);
            }
        }

        private void SetUpperSQDC()
        {
            DataTable dtColor = SQL.ReturnDataTable3(SystemInfo.SQL, "Color_of_SQDC", $"DepartmentID = {SystemInfo.readparentDep} and DateTime = '{DateTime.Now.Date.AddDays(-1)}'");
            if (dtColor.Rows.Count > 0)
            {
                string S = dtColor.Rows[0]["S_Color"].ToString();
                string Q = dtColor.Rows[0]["Q_Color"].ToString();
                string D = dtColor.Rows[0]["D_Color"].ToString();
                string C = dtColor.Rows[0]["C_Color"].ToString();

                switch (S)
                {
                    case "Red":
                        picS.Image = Properties.Resources.S_red;
                        break;
                    case "Green":
                        picS.Image = Properties.Resources.S_green;
                        break;
                    default:
                        break;
                }
                switch (Q)
                {
                    case "Red":
                        picQ.Image = Properties.Resources.Q_red;
                        break;
                    case "Green":
                        picQ.Image = Properties.Resources.Q_green;
                        break;
                    default:
                        break;
                }
                switch (D)
                {
                    case "Red":
                        picD.Image = Properties.Resources.D_red;
                        break;
                    case "Green":
                        picD.Image = Properties.Resources.D_green;
                        break;
                    default:
                        break;
                }
                switch (C)
                {
                    case "Red":
                        picC.Image = Properties.Resources.C_red;
                        break;
                    case "Green":
                        picC.Image = Properties.Resources.C_green;
                        break;
                    default:
                        break;
                }
            }
        }

        public void LoadDepartment(int level, int fac, int parentDep)
        {
            panelControls = new List<PanelControl>
            {
                plDep1,plDep2,plDep3,plDep4,plDep5,plDep6,plDep7,plDep8,plDep9,plDep10,plDep11,plDep12
            };

            labelControls = new List<LabelControl>
            {
                lbDep1,lbDep2,lbDep3,lbDep4,lbDep5,lbDep6,lbDep7,lbDep8,lbDep9,lbDep10,lbDep11,lbDep12
            };

            pictureEdits = new List<PictureEdit>
            {
                picDep1,picDep2,picDep3,picDep4,picDep5,picDep6,picDep7,picDep8,picDep9,picDep10,picDep11,picDep12
            };

            string[] results = GetDataFromDatabase();

            UpdateUI(results, depArray);
        }

        private Image GetImageFromResources(int depID)
        {
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ID = {depID}");
            if (dt.Rows.Count > 0)
            {
                string base64String = dt.Rows[0]["departmentICON"].ToString();
                if (base64String.Length > 0)
                {
                    byte[] bytes = Convert.FromBase64String(base64String);
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        Image image = Image.FromStream(ms);
                        return image;
                    }
                }
                else
                {
                    return Properties.Resources.defaultPic;
                }
            }
            else
            {
                return Properties.Resources.defaultPic;
            }

        }

        private string[] GetDataFromDatabase()
        {
            DataTable dtRelation = SQL.ReturnDataTable3(SystemInfo.SQL, "View_DepRelation", $"mainDepID = {SystemInfo.readparentDep} and [Visit SQDC] = 1 and Confirmed = 1");
            DataTable dtDepartment = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"departmentLevel = {SystemInfo.readLevel} and FactoryID = {SystemInfo.readFactory} and ParentDepartmentID = {SystemInfo.readparentDep} and isDisplay = 1 and Del_tag = 0");

            int depInt = dtDepartment.Rows.Count;
            int relInt = dtRelation.Rows.Count;

            string[] dep = new string[depInt + relInt];
            depArray = new int[depInt + relInt];

            if (depInt > 0)
            {
                for (int i = 0; i < depInt; i++)
                {
                    dep[i] = dtDepartment.Rows[i]["DepartmentName"].ToString();
                    depArray[i] = Convert.ToInt32(dtDepartment.Rows[i]["ID"].ToString());
                }
            }
            if (relInt > 0)
            {
                for (int j = depInt; j < depArray.Length; j++)
                {
                    dep[j] = dtRelation.Rows[j - depInt]["Department name"].ToString();
                    depArray[j] = Convert.ToInt32(dtRelation.Rows[j - depInt]["DepID"].ToString());
                }
            }
            return dep;
        }

        private void SetSQDC(int idx)
        {

            Color colorS = Color.Gray;
            Color colorQ = Color.Gray;
            Color colorD = Color.Gray;
            Color colorC = Color.Gray;
            string Condition3 = $"FactoryID = {SystemInfo.readFactory} and DepartmentID={depArray[idx]} and LevelID={SystemInfo.readLevel} and DateTime='{DateTime.Now.AddDays(-1).Date}' and Del_tag=0";
            DataTable dt1 = SQL.ReturnDataTable3(SystemInfo.SQL, "Color_of_SQDC", Condition3);
            if (dt1.Rows.Count > 0)
            {
                string S = dt1.Rows[0][5].ToString();
                string Q = dt1.Rows[0][6].ToString();
                string D = dt1.Rows[0][7].ToString();
                string C = dt1.Rows[0][8].ToString();
                if (S == "Red")
                {
                    colorS = Color.Red;
                }
                else if (S == "Green")
                {
                    colorS = Color.Lime;
                }
                if (Q == "Red")
                {
                    colorQ = Color.Red;
                }
                else if (Q == "Green")
                {
                    colorQ = Color.Lime;
                }
                if (D == "Red")
                {
                    colorD = Color.Red;
                }
                else if (D == "Green")
                {
                    colorD = Color.Lime;
                }
                if (C == "Red")
                {
                    colorC = Color.Red;
                }
                else if (C == "Green")
                {
                    colorC = Color.Lime;
                }

            }
            xtraScrollableControl1.Controls["plDep" + (idx + 1)].Controls["lbS" + (idx + 1)].ForeColor = colorS;
            xtraScrollableControl1.Controls["plDep" + (idx + 1)].Controls["lbQ" + (idx + 1)].ForeColor = colorQ;
            xtraScrollableControl1.Controls["plDep" + (idx + 1)].Controls["lbD" + (idx + 1)].ForeColor = colorD;
            xtraScrollableControl1.Controls["plDep" + (idx + 1)].Controls["lbC" + (idx + 1)].ForeColor = colorC;
        }
        public void Search_keyCalendar()
        {
            //查询Keycalendar
            string condition = " del_tag = 0 and DATEPART(WK,Due_date) = DATEPART(WK,GETDATE()) and DATEPART(YEAR, Due_date) = DATEPART(YEAR, GETDATE()) and Due_date >= CAST(GETDATE() as DATE) order by Due_date";
            DataTable dt = LSQL.SQL.ReturnDataTable3(SystemInfo.SQL, "[Key_calendar]", condition);

            //循环写入控件
            if (dt.Rows != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //2025-3-4 使用Dev控件更新
                    LabelControl lbDate = new LabelControl();//定义时间文本
                    DateTime date = Convert.ToDateTime(dt.Rows[i]["Due_date"].ToString());
                    lbDate.Text = date.ToString("yyyy-MM-dd");
                    lbDate.Parent = xtraplLeft2;
                    lbDate.Name = dt.Rows[i]["Due_date"].ToString();
                    lbDate.Location = new System.Drawing.Point(14, 13 + i * 85);//102
                    lbDate.AutoSize = true;
                    lbDate.Font = new System.Drawing.Font("Arial", 12);
                    xtraplLeft2.Controls.Add(lbDate);

                    //2025-3-4 使用Dev控件更新
                    LabelControl lbEvent = new LabelControl();//定义事件文本
                    lbEvent.Text = dt.Rows[i]["Key_calendar"].ToString();
                    lbEvent.Parent = xtraplLeft2;
                    lbEvent.Name = dt.Rows[i]["Key_calendar"].ToString();
                    lbEvent.Location = new System.Drawing.Point(14, 37 + i * 85);
                    //lbEvent.AutoSize = false;
                    //lbEvent.Size = new Size(440, 74);
                    lbEvent.AutoEllipsis = true;
                    lbEvent.Font = new System.Drawing.Font("Arial", 15);
                    xtraplLeft2.Controls.Add(lbEvent);

                    //MessageBox.Show($"{plLeft2.Controls.Count}");

                }

            }
        }

        private void SearchGoSee()
        {
            if (SystemInfo.readLevel == maxDepLv)
            {
                string Condition = $"isGoSee = 1 and Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel}) order by ID desc";

                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query0 = $"ID in ({string.Join(",", apIDs)})";
                    DataTable gsdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Gosee", query0);

                    DataTable gsActive = publicFunc.SelectedDatatable(gsdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");

                    gridGOSEEmain.DataSource = gsActive;

                    maingvGosee.Columns["ID"].Visible = false;
                    maingvGosee.Columns["DateTime"].Visible = false;
                    maingvGosee.Columns["负责人姓名"].Visible = false;
                    maingvGosee.Columns["RootCause"].Visible = false;
                    maingvGosee.Columns["负责部门"].Visible = false;
                    maingvGosee.Columns["提出部门"].Visible = false;

                    maingvGosee.Columns["负责部门"].Caption = "Res. Dep";
                    maingvGosee.Columns["TopicINFO"].Caption = "Topic";
                    maingvGosee.Columns["Now_Action"].Caption = "To do/Action";
                    maingvGosee.Columns["Done_tag"].Caption = "Done";

                    maingvGosee.Columns["TopicINFO"].Width = 140;
                    maingvGosee.Columns["Now_Action"].Width = 160;
                    maingvGosee.Columns["Status"].Width = 60;
                    maingvGosee.Columns["Done_tag"].Width = 40;

                    // 创建 ImageComboBoxEdit
                    var repositoryItemImageComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();

                    // 添加预设图片
                    ImageList imageList = new ImageList();
                    imageList.Images.Add("image3", Properties.Resources.进度0);
                    imageList.Images.Add("image3", Properties.Resources.进度25);
                    imageList.Images.Add("image3", Properties.Resources.进度50);
                    imageList.Images.Add("image3", Properties.Resources.进度75);
                    imageList.Images.Add("image3", Properties.Resources.进度100);

                    // 绑定图片到 ImageComboBoxEdit
                    repositoryItemImageComboBox.SmallImages = imageList;
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 1, 0));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 2, 1));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 3, 2));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 4, 3));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 5, 4));


                    maingvGosee.Columns["Status"].ColumnEdit = repositoryItemImageComboBox;

                    maingvGosee.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    maingvGosee.Columns["TopicINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    maingvGosee.Columns["Now_Action"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

                }
            }
            else
            {
                //2025-1-23 修改筛选部门筛选当前等级部门及当前等级部门一下的升级上来的问题
                DataTable depSelect = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");

                string depments = SystemInfo.readparentDep.ToString();
                for (int i = 0; i < depSelect.Rows.Count; i++)
                {
                    depments = depments + $",{depSelect.Rows[i][0].ToString()}";
                }
                string Condition = $"isActionPlan = 1 and (提出部门ID in ({depments}) or 负责部门ID in ({depments})) and Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel}) order by ID desc";
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < apIDs.Length; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query1 = $"ID in ({string.Join(",", apIDs)})";
                    DataTable gsdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_ActionPlan", query1);

                    DataTable gsActive = publicFunc.SelectedDatatable(gsdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    gridGOSEEmain.DataSource = gsActive;
                    maingvGosee.Columns["ID"].Visible = false;
                    maingvGosee.Columns["DateTime"].Visible = false;
                    maingvGosee.Columns["负责人姓名"].Visible = false;
                    maingvGosee.Columns["RootCause"].Visible = false;
                    maingvGosee.Columns["负责部门"].Visible = false;
                    maingvGosee.Columns["提出部门"].Visible = false;

                    maingvGosee.Columns["负责部门"].Caption = "Res. Dep";
                    maingvGosee.Columns["TopicINFO"].Caption = "Topic";
                    maingvGosee.Columns["Now_Action"].Caption = "To do/Action";
                    maingvGosee.Columns["Done_tag"].Caption = "Done";

                    maingvGosee.Columns["TopicINFO"].Width = 140;
                    maingvGosee.Columns["Now_Action"].Width = 160;
                    maingvGosee.Columns["Status"].Width = 60;
                    maingvGosee.Columns["Done_tag"].Width = 40;

                    // 创建 ImageComboBoxEdit
                    var repositoryItemImageComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();

                    // 添加预设图片
                    ImageList imageList = new ImageList();
                    imageList.Images.Add("image3", Properties.Resources.进度0);
                    imageList.Images.Add("image3", Properties.Resources.进度25);
                    imageList.Images.Add("image3", Properties.Resources.进度50);
                    imageList.Images.Add("image3", Properties.Resources.进度75);
                    imageList.Images.Add("image3", Properties.Resources.进度100);

                    // 绑定图片到 ImageComboBoxEdit
                    repositoryItemImageComboBox.SmallImages = imageList;
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 1, 0));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 2, 1));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 3, 2));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 4, 3));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 5, 4));


                    maingvGosee.Columns["Status"].ColumnEdit = repositoryItemImageComboBox;

                    maingvGosee.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    maingvGosee.Columns["TopicINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    maingvGosee.Columns["Now_Action"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                }

            }


        }

        private void SearchFeedback()
        {
            if (SystemInfo.readLevel == maxDepLv)
            {
                string Condition = $"isFeedback = 1 and Curr_level = {SystemInfo.readLevel} or Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel} order by ID desc";

                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query = $"ID in ({string.Join(",", apIDs)})";
                    DataTable fbdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Feedback", query);

                    DataTable fbActive = publicFunc.SelectedDatatable(fbdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    gridFeedbackmain.DataSource = fbActive;

                    maingvFeedback.Columns["ID"].Visible = false;
                    maingvFeedback.Columns["DateTime"].Visible = false;
                    maingvFeedback.Columns["负责人姓名"].Visible = false;
                    maingvFeedback.Columns["RootCause"].Visible = false;
                    maingvFeedback.Columns["负责部门"].Visible = false;
                    maingvFeedback.Columns["提出部门"].Visible = false;

                    maingvFeedback.Columns["负责部门"].Caption = "Res. Dep";
                    maingvFeedback.Columns["TopicINFO"].Caption = "Topic";
                    maingvFeedback.Columns["Now_Action"].Caption = "To do/Action";
                    maingvFeedback.Columns["Done_tag"].Caption = "Done";

                    maingvFeedback.Columns["TopicINFO"].Width = 140;
                    maingvFeedback.Columns["Now_Action"].Width = 160;
                    maingvFeedback.Columns["Status"].Width = 60;
                    maingvFeedback.Columns["Done_tag"].Width = 40;

                    // 创建 ImageComboBoxEdit
                    var repositoryItemImageComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();

                    // 添加预设图片
                    ImageList imageList = new ImageList();
                    imageList.Images.Add("image3", Properties.Resources.进度0);
                    imageList.Images.Add("image3", Properties.Resources.进度25);
                    imageList.Images.Add("image3", Properties.Resources.进度50);
                    imageList.Images.Add("image3", Properties.Resources.进度75);
                    imageList.Images.Add("image3", Properties.Resources.进度100);

                    // 绑定图片到 ImageComboBoxEdit
                    repositoryItemImageComboBox.SmallImages = imageList;
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 1, 0));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 2, 1));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 3, 2));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 4, 3));
                    repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 5, 4));


                    maingvFeedback.Columns["Status"].ColumnEdit = repositoryItemImageComboBox;

                    maingvFeedback.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    maingvFeedback.Columns["TopicINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    maingvFeedback.Columns["Now_Action"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                }
                else
                {
                    //2025-1-23 修改筛选部门筛选当前等级部门及当前等级部门一下的升级上来的问题
                    DataTable depSelect = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");

                    string depments = SystemInfo.readparentDep.ToString();
                    for (int i = 0; i < depSelect.Rows.Count; i++)
                    {
                        depments = depments + $",{depSelect.Rows[i][0].ToString()}";
                    }
                    string Condition1 = $"isFeedback = 1 and (提出部门ID in ({depments}) or 负责部门ID in ({depments})) and Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel}) order by ID desc";
                    DataTable dt1 = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                    if (dt1.Rows.Count > 0)
                    {
                        int[] apIDs = new int[dt1.Rows.Count];
                        for (int i = 0; i < apIDs.Length; i++)
                        {
                            apIDs[i] = (int)dt.Rows[i]["ID"];
                        }
                        string query = $"ID in ({string.Join(",", apIDs)})";
                        DataTable fbdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Feedback", query);

                        DataTable fbActive = publicFunc.SelectedDatatable(fbdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                        gridFeedbackmain.DataSource = fbActive;

                        maingvFeedback.Columns["ID"].Visible = false;
                        maingvFeedback.Columns["DateTime"].Visible = false;
                        maingvFeedback.Columns["负责人姓名"].Visible = false;
                        maingvFeedback.Columns["RootCause"].Visible = false;
                        maingvFeedback.Columns["负责部门"].Visible = false;
                        maingvFeedback.Columns["提出部门"].Visible = false;

                        maingvFeedback.Columns["负责部门"].Caption = "Res. Dep";
                        maingvFeedback.Columns["TopicINFO"].Caption = "Topic";
                        maingvFeedback.Columns["Now_Action"].Caption = "To do/Action";
                        maingvFeedback.Columns["Done_tag"].Caption = "Done";

                        maingvFeedback.Columns["TopicINFO"].Width = 140;
                        maingvFeedback.Columns["Now_Action"].Width = 160;
                        maingvFeedback.Columns["Status"].Width = 60;
                        maingvFeedback.Columns["Done_tag"].Width = 40;

                        // 创建 ImageComboBoxEdit
                        var repositoryItemImageComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();

                        // 添加预设图片
                        ImageList imageList = new ImageList();
                        imageList.Images.Add("image3", Properties.Resources.进度0);
                        imageList.Images.Add("image3", Properties.Resources.进度25);
                        imageList.Images.Add("image3", Properties.Resources.进度50);
                        imageList.Images.Add("image3", Properties.Resources.进度75);
                        imageList.Images.Add("image3", Properties.Resources.进度100);

                        // 绑定图片到 ImageComboBoxEdit
                        repositoryItemImageComboBox.SmallImages = imageList;
                        repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 1, 0));
                        repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 2, 1));
                        repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 3, 2));
                        repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 4, 3));
                        repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 5, 4));


                        maingvFeedback.Columns["Status"].ColumnEdit = repositoryItemImageComboBox;

                        maingvFeedback.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                        maingvFeedback.Columns["TopicINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                        maingvFeedback.Columns["Now_Action"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    }
                }

            }

        }

        private void Initial_lb()
        {
            lbAction1.Text = "";
            lbAction2.Text = "";
            lbAction3.Text = "";
            lbTopic1.Text = "";
            lbTopic2.Text = "";
            lbTopic3.Text = "";

            foreach (XtraControl lb in plRight.Controls)
            {
                if (lb is LabelControl labelControl)
                {
                    labelControl.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                }

            }
        }
        public void LoadTOP3()
        {
            Initial_lb();
            //定义3个整数用于存储topic的ID
            int top1ID = 0;
            int top2ID = 0;
            int top3ID = 0;
            //查询工厂或部门的top问题ID
            DataTable topicID = LSQL.SQL.ReturnDataTable2(SystemInfo.SQL, "Top_Issue_Tag", $"DepartmentID = {SystemInfo.readparentDep} and Date = '{DateTime.Now.Date}'");
            if (topicID != null && topicID.Rows.Count > 0)
            {
                top1ID = (int)topicID.Rows[0]["Top1ID"];
                top2ID = (int)topicID.Rows[0]["Top2ID"];
                top3ID = (int)topicID.Rows[0]["Top3ID"];

                //查询问题详情
                //查询Top1并写入
                DataTable top1 = LSQL.SQL.ReturnDataTable2(SystemInfo.SQL, "Topic", $"ID = {top1ID}");

                if (top1.Rows.Count > 0)
                {
                    lbTopic1.Text = (string)top1.Rows[0]["TopicINFO"];
                }
                DataTable action1 = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "Todo", $"TopicID = {top1ID} and Del_tag = 0");

                if (action1.Rows.Count > 0)
                {
                    for (int i = 0; i < action1.Rows.Count; i++)
                    {
                        lbAction1.Text += $"{i + 1}. {action1.Rows[i]["TodoINFO"].ToString()};\n";
                    }
                }

                //查询Top2并写入
                DataTable top2 = LSQL.SQL.ReturnDataTable2(SystemInfo.SQL, "Topic", $"ID = {top2ID}");

                if (top2.Rows.Count > 0)
                {
                    lbTopic2.Text = (string)top2.Rows[0]["TopicINFO"];
                }
                DataTable action2 = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "Todo", $"TopicID = {top2ID}");

                if (action2.Rows.Count > 0)
                {
                    for (int i = 0; i < action2.Rows.Count; i++)
                    {
                        lbAction2.Text += $"{i + 1}. {action2.Rows[i]["TodoINFO"].ToString()};\n";
                    }
                }

                //查询Top1并写入
                DataTable top3 = LSQL.SQL.ReturnDataTable2(SystemInfo.SQL, "Topic", $"ID = {top3ID}");

                if (top3.Rows.Count > 0)
                {
                    lbTopic3.Text = (string)top3.Rows[0]["TopicINFO"];
                }
                DataTable action3 = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "Todo", $"TopicID = {top3ID}");

                if (action3.Rows.Count > 0)
                {
                    for (int i = 0; i < action3.Rows.Count; i++)
                    {
                        lbAction3.Text += $"{i + 1}. {action3.Rows[i]["TodoINFO"].ToString()};\n";
                    }
                }

            }

        }


        private void DepPanelClick(object sender, EventArgs e)
        {
            if (plMain.Controls.Count > 0)  // 确保 Panel 里至少有一个控件
            {
                Control firstControl = plMain.Controls[0];  // 获取索引为 0 的控件

                if (firstControl.Name != "Form_Department") // 你可以用 Name 来判断
                {
                    Form_Department dep = new Form_Department();

                    dep.FactoryID = SystemInfo.readFactory;
                    PanelControl pl = sender as PanelControl;
                    int index = Convert.ToInt32(pl.Name.Replace("plDep", "")) - 1;
                    Form_Department.DepartmentID = depArray[index];
                    dep.Level = SystemInfo.readLevel;

                    //Display_dep(dep);
                    dep.TopLevel = false;
                    this.plMain.Controls.Add(dep);
                    dep.BringToFront();
                    dep.Show();
                }
            }

        }
        #endregion

        #region 问题——Deviation

        public int timeCondition;

        // 存储当前排序和滚动位置的变量
        private Dictionary<string, DevExpress.Data.ColumnSortOrder> currentSortInfo = new Dictionary<string, DevExpress.Data.ColumnSortOrder>();
        private int currentTopRowIndex = 0;
        private int currentLeftCoord = 0;
        private object currentFocusedRowKey = null;

        // 需要隐藏的列名列表（可根据需要修改）
        private readonly string[] hiddenColumns = { "isConfirmation" }; // 示例：隐藏确认列

        private void Write2GridView(DataTable dt)
        {
            // 保存当前状态
            SaveCurrentGridState();

            gvDeviation.BeginDataUpdate();

            gridControl1.DataSource = dt;
            gvDeviation.OptionsView.ShowIndicator = false;
            //gvDeviation.PopulateColumns();  // 确保生成列

            gvDeviation.Columns.Clear(); // 不要清除列，否则后面代码会出错

            gvDeviation.Columns.AddVisible("isConfirmation", " ");
            gvDeviation.Columns.AddVisible("ID", "No.");
            gvDeviation.Columns.AddVisible("DateTime", "Date");
            gvDeviation.Columns.AddVisible("提出部门", "Assigned by");
            gvDeviation.Columns.AddVisible("TopicINFO", "Topic");
            gvDeviation.Columns.AddVisible("RootCause", "Root cause");
            gvDeviation.Columns.AddVisible("TodoINFO", "Action");
            gvDeviation.Columns.AddVisible("负责部门", "Res. department");
            gvDeviation.Columns.AddVisible("负责人姓名", "Res. person");
            gvDeviation.Columns.AddVisible("DueDate", "Due on");
            gvDeviation.Columns.AddVisible("Status", "Status");

            // 隐藏指定的列
            HideSpecifiedColumns();

            //设置文本列不可编辑
            gvDeviation.Columns["ID"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["DateTime"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["提出部门"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["TopicINFO"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["RootCause"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["TodoINFO"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["负责部门"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["负责人姓名"].OptionsColumn.AllowEdit = false;
            gvDeviation.Columns["DueDate"].OptionsColumn.AllowEdit = true;
            gvDeviation.Columns["Status"].OptionsColumn.AllowEdit = true;  // 让图片列可编辑

            // 配置日期列
            var repositoryItemDateEdit = new DevExpress.XtraEditors.Repository.RepositoryItemDateEdit();
            repositoryItemDateEdit.CalendarTimeProperties.DisplayFormat.FormatString = "yyyy-MM-dd";
            repositoryItemDateEdit.CalendarTimeProperties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            repositoryItemDateEdit.Mask.EditMask = "yyyy-MM-dd";
            repositoryItemDateEdit.Mask.UseMaskAsDisplayFormat = true;

            // 确保不重复添加 RepositoryItem
            if (!gridControl1.RepositoryItems.Contains(repositoryItemDateEdit))
            {
                gridControl1.RepositoryItems.Add(repositoryItemDateEdit);
            }

            // 创建 ImageComboBoxEdit
            var repositoryItemImageComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();

            // 添加预设图片
            ImageList imageList = new ImageList();
            imageList.Images.Add("image3", Properties.Resources.进度0);
            imageList.Images.Add("image3", Properties.Resources.进度25);
            imageList.Images.Add("image3", Properties.Resources.进度50);
            imageList.Images.Add("image3", Properties.Resources.进度75);
            imageList.Images.Add("image3", Properties.Resources.进度100);

            // 绑定图片到 ImageComboBoxEdit
            repositoryItemImageComboBox.SmallImages = imageList;
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 0%", 1, 0));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 25%", 2, 1));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 50%", 3, 2));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 75%", 4, 3));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 100%", 5, 4));


            gvDeviation.Columns["Status"].ColumnEdit = repositoryItemImageComboBox;
            // 确保不重复添加 RepositoryItem
            if (!gridControl1.RepositoryItems.Contains(repositoryItemImageComboBox))
            {
                gridControl1.RepositoryItems.Add(repositoryItemImageComboBox);
            }


            // 正确设置列宽（使用真实列名）
            gvDeviation.Columns["isConfirmation"].Width = 50;
            gvDeviation.Columns["ID"].Width = 80;
            gvDeviation.Columns["DateTime"].Width = 100;
            gvDeviation.Columns["提出部门"].Width = 128;
            gvDeviation.Columns["TopicINFO"].Width = 380;
            gvDeviation.Columns["RootCause"].Width = 357;
            gvDeviation.Columns["TodoINFO"].Width = 380;
            gvDeviation.Columns["负责部门"].Width = 128;
            gvDeviation.Columns["负责人姓名"].Width = 120;
            gvDeviation.Columns["DueDate"].Width = 100;
            gvDeviation.Columns["Status"].Width = 110;

            //设置字体
            gvDeviation.Appearance.Row.Font = new Font("Tahoma", 12, FontStyle.Regular);
            gvDeviation.Appearance.HeaderPanel.Font = new Font("Tahoma", 12, FontStyle.Bold);
            gvDeviation.Appearance.HeaderPanel.BackColor = Color.FromArgb(30, 42, 99);
            gvDeviation.Appearance.HeaderPanel.ForeColor = Color.FromArgb(0, 0, 0);

            //设置自动换行
            // 允许行高自动调整
            gvDeviation.OptionsView.RowAutoHeight = true;

            // 让所有行都能换行
            gvDeviation.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

            // 让特定列换行
            gvDeviation.Columns["TopicINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvDeviation.Columns["RootCause"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvDeviation.Columns["TodoINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvDeviation.Columns["提出部门"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvDeviation.Columns["负责部门"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvDeviation.Columns["负责人姓名"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

            // 让单元格可以输入多行文本
            var memoEdit = new DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit();
            gvDeviation.Columns["TopicINFO"].ColumnEdit = memoEdit;
            gvDeviation.Columns["RootCause"].ColumnEdit = memoEdit;
            gvDeviation.Columns["TodoINFO"].ColumnEdit = memoEdit;
            gvDeviation.Columns["提出部门"].ColumnEdit = memoEdit;
            gvDeviation.Columns["负责部门"].ColumnEdit = memoEdit;
            gvDeviation.Columns["负责人姓名"].ColumnEdit = memoEdit;

            // 确保 RepositoryItem 绑定到 GridControl
            if (!gridControl1.RepositoryItems.Contains(memoEdit))
            {
                gridControl1.RepositoryItems.Add(memoEdit);
            }

            gvDeviation.EndDataUpdate();

            // 恢复之前的状态
            RestoreGridState();
        }

        /// <summary>
        /// 保存当前网格状态（排序、滚动位置、焦点行）
        /// </summary>
        private void SaveCurrentGridState()
        {
            if (gvDeviation.DataSource != null && gvDeviation.RowCount > 0)
            {
                // 保存排序信息
                currentSortInfo.Clear();
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gvDeviation.Columns)
                {
                    if (column.SortOrder != DevExpress.Data.ColumnSortOrder.None)
                    {
                        currentSortInfo[column.FieldName] = column.SortOrder;
                    }
                }

                // 保存滚动位置
                currentTopRowIndex = gvDeviation.TopRowIndex;
                currentLeftCoord = gvDeviation.LeftCoord;

                // 保存焦点行的主键值
                if (gvDeviation.FocusedRowHandle >= 0)
                {
                    currentFocusedRowKey = gvDeviation.GetRowCellValue(gvDeviation.FocusedRowHandle, "ID");
                }
            }
        }

        /// <summary>
        /// 恢复网格状态（排序、滚动位置、焦点行）
        /// </summary>
        private void RestoreGridState()
        {
            if (gvDeviation.DataSource != null && gvDeviation.RowCount > 0)
            {
                try
                {
                    // 恢复排序
                    if (currentSortInfo.Count > 0)
                    {
                        gvDeviation.ClearSorting();
                        foreach (var sortInfo in currentSortInfo)
                        {
                            if (gvDeviation.Columns[sortInfo.Key] != null)
                            {
                                gvDeviation.Columns[sortInfo.Key].SortOrder = sortInfo.Value;
                            }
                        }
                    }

                    // 恢复焦点行
                    if (currentFocusedRowKey != null)
                    {
                        for (int i = 0; i < gvDeviation.DataRowCount; i++)
                        {
                            var rowKey = gvDeviation.GetRowCellValue(i, "ID");
                            if (rowKey != null && rowKey.Equals(currentFocusedRowKey))
                            {
                                gvDeviation.FocusedRowHandle = i;
                                break;
                            }
                        }
                    }

                    // 恢复滚动位置（延迟执行）
                    System.Windows.Forms.Application.DoEvents();
                    if (currentTopRowIndex < gvDeviation.DataRowCount)
                    {
                        gvDeviation.TopRowIndex = currentTopRowIndex;
                    }
                    gvDeviation.LeftCoord = currentLeftCoord;
                }
                catch
                {
                    // 如果恢复失败，忽略错误
                }
            }
        }

        /// <summary>
        /// 隐藏指定的列
        /// </summary>
        private void HideSpecifiedColumns()
        {
            foreach (string columnName in hiddenColumns)
            {
                if (gvDeviation.Columns[columnName] != null)
                {
                    gvDeviation.Columns[columnName].Visible = false;
                }
            }
        }

        public void LoadDeviation(int time)
        {
            CountNewTopics();
            int maxLv = publicFunc.MaxDepartmentLevel();

            if (SystemInfo.readLevel == maxLv)
            {
                string Condition = $"Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel}) and Create_time >= '{DateTime.Now.AddDays(-365)}' order by ID desc";
                DataTable dtDeviation = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                //Write2GridView(dtDeviation);
                WriteByTime(dtDeviation, time);
            }
            else
            {
                string departmentPath = $@"-- 假设要查询ID为1的部门的所有子部门
DECLARE @DepartmentID int = {SystemInfo.readparentDep};

WITH DepartmentHierarchy AS (
    -- 基础查询
    SELECT 
        ID,
        DepartmentName,
        ParentDepartmentID,
        departmentLevel,
        1 as Level,
        CAST(DepartmentName as nvarchar(1000)) as Path
    FROM Departments
    WHERE ParentDepartmentID = @DepartmentID
    
    UNION ALL
    
    -- 递归部分
    SELECT 
        d.ID,
        d.DepartmentName,
        d.ParentDepartmentID,
        d.departmentLevel,
        dh.Level + 1,
        CAST(dh.Path + ' > ' + d.DepartmentName as nvarchar(1000))
    FROM Departments d
    INNER JOIN DepartmentHierarchy dh ON d.ParentDepartmentID = dh.ID
    WHERE d.Del_tag = 0
)
SELECT 
    ID,
    DepartmentName,
    ParentDepartmentID,
    departmentLevel,
    Level as HierarchyLevel,
    Path as DepartmentPath
FROM DepartmentHierarchy
ORDER BY Level, ID;";
                //2025-1-23 修改筛选部门筛选当前等级部门及当前等级部门一下的升级上来的问题
                DataTable depSelect = SQL.ReturnDataTable(SystemInfo.SQL, departmentPath);
                DataTable depSlave = SQL.ReturnDataTable3(SystemInfo.SQL, "DepRelation", $"mainDepID = {SystemInfo.readparentDep} and Del_tag = 0 and isTopic = 1 and isConfirm = 1");

                string depments = SystemInfo.readparentDep.ToString();
                string idSlaves = "";
                for (int i = 0; i < depSelect.Rows.Count; i++)
                {
                    depments = depments + $",{depSelect.Rows[i][0].ToString()}";
                }
                if (depSlave.Rows.Count > 0)
                {
                    for (int j = 0; j < depSlave.Rows.Count; j++)
                    {
                        idSlaves = idSlaves + $",{depSlave.Rows[j]["DepID"].ToString()}";

                    }
                    idSlaves = idSlaves.Substring(1);
                }
                if (idSlaves.Length == 0)
                {
                    idSlaves = "0";
                }
                //string Condition = $"(提出部门ID in ({depments}) or 负责部门ID in ({depments})) and (Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel})) and Create_time >= '{DateTime.Now.AddDays(-365)}' order by ID desc";
                string Condition = $"(Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate >= {SystemInfo.readLevel})) and Create_time >= '{DateTime.Now.AddDays(-365)}' order by ID desc";
                //(提出部门ID in (39, 56, 59, 60, 64, 66, 97, 109, 119, 120) or 负责部门ID in (39, 56, 59, 60, 64, 66, 97, 109, 119, 120)) and Curr_level = 3 or(Curr_level <= 3 and isUpdate = 3)
                DataTable dtDeviation = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                //DataTable dtSelect = publicFunc.SelectedDatatable(dtDeviation, $"提出部门ID in ({depments}) and (负责部门ID in ({depments}) or 负责部门ID in ({idSlaves}))");
                DataTable dtSelect = publicFunc.SelectedDatatable(dtDeviation, $"(提出部门ID in ({depments}) or 负责部门ID in ({depments})) or (提出部门ID in ({depments}) and 负责部门ID in ({idSlaves}))");
                //Write2GridView(dtDeviation);
                //WriteByTime(dtDeviation, time);
                WriteByTime(dtSelect, time);
            }
        }

        private void WriteByTime(DataTable dataTable, int time)
        {

            DataRow[] dr1 = dataTable.Select("DueDate>='" + DateTime.Now.AddDays(-1) + "' and isConfirmation=0");
            DataRow[] dr2 = dataTable.Select("DueDate<'" + DateTime.Now.AddDays(-1) + "' and isConfirmation=0");

            // 创建与 dataTable 结构相同的 DataTable
            DataTable dt1 = dataTable.Clone();  // 存放 dr1 的数据
            DataTable dt2 = dataTable.Clone();  // 存放 dr2 的数据

            // 将 dr1 数据添加到 dt1
            foreach (DataRow row in dr1)
            {
                dt1.ImportRow(row);
            }

            // 将 dr2 数据添加到 dt2
            foreach (DataRow row in dr2)
            {
                dt2.ImportRow(row);
            }


            lbActive.Text = dr1.Length.ToString();
            lbOverdue.Text = dr2.Length.ToString();
            lbTotal.Text = dataTable.Rows.Count.ToString();

            switch (time)
            {
                case 1:
                    Write2GridView(dt1);
                    break;
                case 2:
                    Write2GridView(dt2);
                    break;
                case 3:
                    Write2GridView(dataTable);
                    break;
            }
        }

        private void lbActive_Click(object sender, EventArgs e)
        {
            timeCondition = 1;
            // 如果没有保存的排序信息，则设置默认排序
            if (currentSortInfo.Count == 0)
            {
                currentSortInfo["DateTime"] = DevExpress.Data.ColumnSortOrder.Descending;
            }
            LoadDeviation(timeCondition);
            palActive.BackColor = Color.LimeGreen;
            palOverdue.BackColor = Color.Transparent;
            palTotal.BackColor = Color.Transparent;
        }

        private void lbOverdue_Click(object sender, EventArgs e)
        {
            timeCondition = 2;
            // 如果没有保存的排序信息，则设置默认排序
            if (currentSortInfo.Count == 0)
            {
                currentSortInfo["DateTime"] = DevExpress.Data.ColumnSortOrder.Descending;
            }
            LoadDeviation(timeCondition);
            palActive.BackColor = Color.Transparent;
            palOverdue.BackColor = Color.LimeGreen;
            palTotal.BackColor = Color.Transparent;
        }

        private void lbTotal_Click(object sender, EventArgs e)
        {
            timeCondition = 3;
            // 如果没有保存的排序信息，则设置默认排序
            if (currentSortInfo.Count == 0)
            {
                currentSortInfo["DateTime"] = DevExpress.Data.ColumnSortOrder.Descending;
            }
            LoadDeviation(timeCondition);
            palActive.BackColor = Color.Transparent;
            palOverdue.BackColor = Color.Transparent;
            palTotal.BackColor = Color.LimeGreen;
        }

        private bool isDataModified;
        private void gvDeviation_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "DueDate" || e.Column.FieldName == "DateTime" || e.Column.FieldName == "Status")
            {
                isDataModified = true; // 记录修改状态
                btnSave.Visible = true;
                // 弹出提示框提醒用户保存
                XtraMessageBox.Show("数据已修改，请点击保存按钮提交更改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            //Topic_Action.isNewAction = true; //定义为新建标识
            Topic_Action.isNewTopic = true; //定义为新建标识
            Topic_Action.instance.navigationFrame1.SelectedPageIndex = 1;
            Topic_Action.instance.ShowDialog();

        }

        private int rowIndex = -1;
        private void gvDeviation_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right )
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    rowIndex = hitInfo.RowHandle;
                    deviationPopMenu.ShowPopup(Control.MousePosition); // 在鼠标位置显示菜单
                }
            }
            else if ( e.Button == MouseButtons.Left)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    rowIndex = hitInfo.RowHandle;
                }
            }
        }
        private void btnDeviDone_ItemClick(object sender, ItemClickEventArgs e)
        {
            int TodoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            int todoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);

            //添加是否是责任人
            int assignPer = publicFunc.AssignPersonID(todoID);

            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false && assignPer != SystemInfo.userID)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            // 获取当前选中行Status列的值
            object statusValue = gvDeviation.GetFocusedRowCellValue("Status");
            if (statusValue != null)
            {
                // 如果是ImageComboBoxItem的值，需要转换
                int selectedValue = Convert.ToInt32(statusValue);
                // selectedValue对应你设置的值：1=0%, 2=25%, 3=50%, 4=75%, 5=100%
                if (selectedValue != 5)
                {
                    XtraMessageBox.Show(LookAndFeel, "该问题进度未达到100%");
                    return;
                }
                bool update = SQL.Update(SystemInfo.SQL, "Todo", "isConfirmation = 1", $"ID = {TodoID}");
                if (update)
                {
                    XtraMessageBox.Show("To do/Action设置为完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadDeviation(timeCondition);
                }

            }
        }
        private void modifyTopic_ItemClick(object sender, ItemClickEventArgs e)
        {
            //修改Topic
            int todoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            Topic_Action.TopicID = publicFunc.GetTopicID(todoID);
            Topic_Action.isNewTopic = false;
            Topic_Action.instance.navigationFrame1.SelectedPageIndex = 1;
            Topic_Action.instance.ShowDialog();
            rowIndex = -1;

        }

        private void modifyAction_ItemClick(object sender, ItemClickEventArgs e)
        {
            //修改Todo
            int todoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            Topic_Action.TodoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            Topic_Action.isNewAction = false;
            Topic_Action.isNewTopic = false;
            Topic_Action.instance.navigationFrame1.SelectedPageIndex = 0;
            Topic_Action.instance.ShowDialog();
            rowIndex = -1;
        }

        private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
        {
            //给Topic添加新Action
            int todoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            Topic_Action.TopicID = publicFunc.GetTopicID(todoID);
            Topic_Action.isNewTopic = false;
            Topic_Action.isNewAction = true;
            Topic_Action.instance.navigationFrame1.SelectedPageIndex = 0;
            Topic_Action.instance.ShowDialog();
            rowIndex = -1;
        }
        private void barBtnToCIP_ItemClick(object sender, ItemClickEventArgs e)
        {
            //给Topic添加新Action
            int todoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            DataTable dtTopic = SQL.ReturnDataTable3(SystemInfo.SQL, "Todo", $"ID = {todoID}");
            int topicID = (int)dtTopic.Rows[0]["TopicID"];
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            CIPAdd.isEdit = false;
            CIPAdd.isDeviation = true;
            CIPAdd.TopicID = topicID;
            CIPAdd cipadd = new CIPAdd();
            CIPAdd.instance.textTopic.Text = gvDeviation.GetRowCellValue(rowIndex, "TopicINFO").ToString();
            cipadd.ShowDialog();
            //CIPAdd.instance.ShowDialog();



        }
        //需要权限
        private void btnSave_Click(object sender, EventArgs e)
        {
            //if (!isDataModified)
            //{
            //    XtraMessageBox.Show("没有需要保存的更改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            gvDeviation.CloseEditor();  // 确保 GridView 结束编辑状态
            gvDeviation.UpdateCurrentRow();

            DataTable dt = (DataTable)gridControl1.DataSource; // 获取绑定的数据
            bool hasUpdates = false;

            foreach (DataRow row in dt.Rows)
            {
                if (row.RowState == DataRowState.Modified) // 只更新被修改的行
                {
                    string id = row["ID"].ToString();
                    string dueDate = row["DueDate"].ToString();
                    string statusPic = row["Status"].ToString();

                    bool update = SQL.Update(SystemInfo.SQL, "Todo", $"DueDate = '{dueDate}',Status = '{statusPic}'", $"ID = {id}");

                    if (update)
                    {
                        hasUpdates = true;
                    }
                }
            }

            if (hasUpdates)
            {
                XtraMessageBox.Show("数据已成功保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 重新加载数据，刷新 GridView（保持当前状态）
                LoadDeviation(timeCondition);
            }

            // 取消修改标记
            isDataModified = false;
            btnSave.Visible = false;
        }

        //设置Top issue
        private void SetTop(int i, GridView gv, int gvIndex)
        {
            int todoID = Convert.ToInt32(gv.GetRowCellValue(gvIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            DataTable topic = SQL.ReturnDataTable3(SystemInfo.SQL, "Todo", $"ID = {todoID}");
            int topicID = (int)topic.Rows[0]["TopicID"];
            //查询今天的Top issue里有没有数据
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Top_Issue_Tag", $"Date = '{DateTime.Now.Date}' and DepartmentID = {SystemInfo.readparentDep}");
            if (dt.Rows.Count > 0)
            {
                bool res = SQL.Update(SystemInfo.SQL, "Top_Issue_Tag", $"Top{i}ID = {topicID}", $"ID = {(int)dt.Rows[0]["ID"]}");
                if (res)
                {
                    bool updateTopic = SQL.Update(SystemInfo.SQL, "Topic", $"Curr_top = {i}", $"ID = {topicID}");
                    if (updateTopic)
                    {
                        //
                        XtraMessageBox.Show(LookAndFeel, $"成功设置为Top{i}");
                        gvIndex = -1;
                    }

                }
            }
            else
            {
                int res = SQL.InsertReturnID(SystemInfo.SQL, "Top_Issue_Tag", $"DepartmentID,Top{i}ID,Date,Create_userID,FactoryID", $"{SystemInfo.readparentDep},{topicID},'{DateTime.Now.Date}',{SystemInfo.userID},{SystemInfo.readFactory}");
                if (res > 0)
                {
                    bool updateTopic = SQL.Update(SystemInfo.SQL, "Topic", $"Curr_top = {i}", $"ID = {topicID}");
                    if (updateTopic)
                    {
                        XtraMessageBox.Show(LookAndFeel, $"成功设置为Top{i}");
                        gvIndex = -1;
                    }
                }
            }
        }

        private void SetDiffTop(int i, GridView gv, int gvIndex)
        {
            int todoID = Convert.ToInt32(gv.GetRowCellValue(gvIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            DataTable topic = SQL.ReturnDataTable3(SystemInfo.SQL, "Todo", $"ID = {todoID}");
            int topicID = (int)topic.Rows[0]["TopicID"];

            //查询今天的Top issue里有没有数据
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Top_Issue_Tag_Level", $"Date = '{DateTime.Now.Date}' and DepartmentID = {SystemInfo.readparentDep} and Top_level = {SystemInfo.readLevel}");
            if (dt.Rows.Count > 0)
            {
                bool res = SQL.Update(SystemInfo.SQL, "Top_Issue_Tag_Level", $"Top{i}ID = {topicID}", $"ID = {(int)dt.Rows[0]["ID"]}");
                if (res)
                {
                    DialogResult result = XtraMessageBox.Show(LookAndFeel, "是否升级到上层Top", "是否升级", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //升级到上层Top
                        DataTable dtUpper = SQL.ReturnDataTable3(SystemInfo.SQL, "Top_Issue_Tag_Level", $"Date = '{DateTime.Now.Date}' and DepartmentID = {SystemInfo.readparentDep} and Top_level = {SystemInfo.readLevel + 1}");
                        if (dtUpper.Rows.Count > 0)
                        {
                            bool update2UpperLevel = SQL.Update(SystemInfo.SQL, "Top_Issue_Tag_Level", $"Top{i}ID = {topicID}", $"ID = {(int)dtUpper.Rows[0]["ID"]}");
                            if (update2UpperLevel)
                            {
                                XtraMessageBox.Show(LookAndFeel, $"成功升级到上层Top");
                                gvIndex = -1;
                            }
                        }
                        else
                        {
                            int insert2UpperLevel = SQL.InsertReturnID(SystemInfo.SQL, "Top_Issue_Tag_Level", $"DepartmentID,Top{i}ID,Date,Create_userID,FactoryID,Top_level", $"{SystemInfo.readparentDep},{topicID},'{DateTime.Now.Date}',{SystemInfo.userID},{SystemInfo.readFactory},{SystemInfo.readLevel + 1}");
                            if (insert2UpperLevel > 0)
                            {
                                XtraMessageBox.Show(LookAndFeel, $"成功升级到上层Top");
                                gvIndex = -1;
                            }
                        }
                    }
                    bool updateTopic = SQL.Update(SystemInfo.SQL, "Topic", $"Curr_top = {i}", $"ID = {topicID}");
                    if (updateTopic)
                    {
                        //
                        XtraMessageBox.Show(LookAndFeel, $"成功设置为Top{i}");
                        gvIndex = -1;
                    }

                }
            }
            else
            {
                int res = SQL.InsertReturnID(SystemInfo.SQL, "Top_Issue_Tag_Level", $"DepartmentID,Top{i}ID,Date,Create_userID,FactoryID,Top_level", $"{SystemInfo.readparentDep},{topicID},'{DateTime.Now.Date}',{SystemInfo.userID},{SystemInfo.readFactory},{SystemInfo.readLevel}");
                if (res > 0)
                {
                    bool updateTopic = SQL.Update(SystemInfo.SQL, "Topic", $"Curr_top = {i}", $"ID = {topicID}");
                    if (updateTopic)
                    {
                        XtraMessageBox.Show(LookAndFeel, $"成功设置为Top{i}");
                        gvIndex = -1;
                    }
                }
            }
        }

        private void RemoveTop(GridView gv, int gvIndex)
        {
            int todoID = Convert.ToInt32(gv.GetRowCellValue(gvIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            DataTable topic = SQL.ReturnDataTable3(SystemInfo.SQL, "Todo", $"ID = {todoID}");
            int topicID = (int)topic.Rows[0]["TopicID"];

            DataTable dtTag = SQL.ReturnDataTable3(SystemInfo.SQL, "Top_Issue_Tag", $"DepartmentID = {SystemInfo.readparentDep} and Date = '{DateTime.Now.Date}'");
            if (dtTag.Rows.Count > 0)
            {
                for (int i = 1; i <= 3; i++)
                {
                    if ((int)dtTag.Rows[0][$"Top{i}ID"] == topicID)
                    {
                        bool res = SQL.Update(SystemInfo.SQL, "Top_Issue_Tag", $"Top{i}ID = 0", $"ID = {(int)dtTag.Rows[0]["ID"]}");
                        if (res)
                        {
                            gvIndex = -1;
                            XtraMessageBox.Show(LookAndFeel, $"成功移除Top{i}");
                            break;
                        }
                    }

                }

            }
        }
        private void btnSetTop1_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetTop(1, gvDeviation, rowIndex);

        }

        private void btnSetTop2_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetTop(2, gvDeviation, rowIndex);
        }

        private void btnSetTop3_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetTop(3, gvDeviation, rowIndex);
        }

        private void btnRemoveTop_ItemClick(object sender, ItemClickEventArgs e)
        {
            RemoveTop(gvDeviation, rowIndex);
        }
        private void itemBtnUpdate_ItemClick(object sender, ItemClickEventArgs e)
        {
            int todoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            DataTable todo = SQL.ReturnDataTable3(SystemInfo.SQL, "Todo", $"ID = {todoID}");
            int topicID = (int)todo.Rows[0]["TopicID"];
            DataTable topic = SQL.ReturnDataTable3(SystemInfo.SQL, "Topic", $"ID = {topicID}");
            int curr_Lv = (int)topic.Rows[0]["Curr_level"];
            int isUpdate = (int)topic.Rows[0]["isUpdate"];
            if (curr_Lv < maxDepLv)
            {
                int newUpdateLv;
                if (isUpdate < curr_Lv)
                {
                    newUpdateLv = curr_Lv + 1;
                }
                else
                {
                    if (isUpdate == maxDepLv)
                    {
                        XtraMessageBox.Show("已经升级为L4问题，无法升级!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else
                    {
                        newUpdateLv = isUpdate + 1;
                    }
                }
                DialogResult dr = MessageBox.Show("确认将问题升级至L" + newUpdateLv + "?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dr == DialogResult.OK)
                {
                    if (SQL.Update(SystemInfo.SQL, "Topic", "isUpdate=" + newUpdateLv, "ID=" + topicID) == true)
                    {

                        LoadDeviation(timeCondition);
                    }
                }
            }
            else
            {
                XtraMessageBox.Show("已经升级为L4问题，无法升级!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            int todoID = Convert.ToInt32(gvDeviation.GetRowCellValue(rowIndex, "ID"));
            int topicID = publicFunc.GetTopicID(todoID);
            int resID = publicFunc.ResDepID(todoID);
            int assignID = publicFunc.AssignDepID(todoID);
            if (publicFunc.GetUserScope(SystemInfo.userID, resID) == false && publicFunc.GetUserScope(SystemInfo.userID, assignID) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            DataTable dtTop = SQL.ReturnDataTable3(SystemInfo.SQL, "Top_Issue_Tag", $"Top1ID = {topicID} or Top2ID = {topicID} or Top3ID = {topicID}");
            if (dtTop.Rows.Count > 0)
            {
                DialogResult result = XtraMessageBox.Show(LookAndFeel, "此问题已被定义为Top,是否删除？", "确认", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    string idx = "0";
                    for (int i = 1; i < 4; i++)
                    {
                        if ((int)dtTop.Rows[0][$"Top{i}ID"] == topicID)
                        {
                            idx = i.ToString();
                        }
                    }
                    bool updateTop = SQL.Update(SystemInfo.SQL, "Top_Issue_Tag", $"Top{idx}ID = 0", $"ID = {(int)dtTop.Rows[0]["ID"]}");
                    bool updateTopic = SQL.Update(SystemInfo.SQL, "Todo", "Del_tag = 1", $"ID = {todoID}");

                    if (updateTop && updateTopic)
                    {
                        //查询是否被定义为Top，询问用户是否删除
                        XtraMessageBox.Show("已经成功删除!", "Delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadDeviation(timeCondition);
                    }
                }
                if (result == DialogResult.No)
                {
                    return;
                }
            }
            else
            {
                if (SQL.Update(SystemInfo.SQL, "Todo", "Del_tag = 1", $"ID = {todoID}"))
                {
                    //查询是否被定义为Top，询问用户是否删除
                    XtraMessageBox.Show("已经成功删除!", "Delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadDeviation(timeCondition);
                }
            }

        }

        private void CountNewTopics()
        {
            //查询部门序列
            string depCondition = $@"-- 假设要查询ID为1的部门的所有子部门
DECLARE @DepartmentID int = {SystemInfo.readparentDep};

WITH DepartmentHierarchy AS (
    -- 基础查询
    SELECT 
        ID,
        DepartmentName,
        ParentDepartmentID,
        departmentLevel,
        1 as Level,
        CAST(DepartmentName as nvarchar(1000)) as Path
    FROM Departments
    WHERE ParentDepartmentID = @DepartmentID
    
    UNION ALL
    
    -- 递归部分
    SELECT 
        d.ID,
        d.DepartmentName,
        d.ParentDepartmentID,
        d.departmentLevel,
        dh.Level + 1,
        CAST(dh.Path + ' > ' + d.DepartmentName as nvarchar(1000))
    FROM Departments d
    INNER JOIN DepartmentHierarchy dh ON d.ParentDepartmentID = dh.ID
    WHERE d.Del_tag = 0
)
SELECT 
    ID,
    DepartmentName,
    ParentDepartmentID,
    departmentLevel,
    Level as HierarchyLevel,
    Path as DepartmentPath
FROM DepartmentHierarchy
ORDER BY Level, ID;";
            DataTable dtDep = SQL.ReturnDataTable(SystemInfo.SQL, depCondition);
            string depIDs = string.Join(",", dtDep.AsEnumerable()
                                                .Select(row => row["ID"].ToString())
                                                .Distinct());
            if (depIDs.Length > 0)
            {
                // 获取本周一（只包含日期）
                DateTime monday = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek + 1).Date;
                // 获取本周日（只包含日期）
                DateTime sunday = monday.AddDays(6).Date;

                // 如果需要格式化输出
                string mondayStr = monday.ToString("yyyy-MM-dd");  // 例如：2024-03-18
                string sundayStr = sunday.ToString("yyyy-MM-dd");  // 例如：2024-03-24
                string condition = $"(提出部门ID IN ({depIDs}) or 负责部门ID IN ({depIDs})) and (DateTime between '{mondayStr}' and '{sundayStr}') and isConfirmation = 0";
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", condition);
                int count = dt.Rows.Count;
                lblNewTopic.Text = $"New topic(week): {count}";

                double a = Convert.ToInt32(lbTotal.Text);
                double b = Convert.ToInt32(lbOverdue.Text);

                double res = (a - b) * 100 / a;
                lblCompletion.Text = $"Completion rate: {res.ToString("0.00")}%";
            }

           
        }

        private void CountCompletionRate()
        {

        }

        // 存储滚动条位置的公共变量
        public static Point GridScrollPosition = Point.Empty;

        /// <summary>
        /// 保存GridControl的滚动条位置
        /// </summary>
        /// <param name="gridControl">GridControl控件</param>
        public static void SaveGridScrollPosition(GridControl gridControl)
        {
            if (gridControl?.MainView is GridView gridView)
            {
                GridScrollPosition = new Point(
                    gridView.LeftCoord,
                    gridView.TopRowIndex
                );
            }
        }

        /// <summary>
        /// 恢复GridControl的滚动条位置
        /// </summary>
        /// <param name="gridControl">GridControl控件</param>
        public static void RestoreGridScrollPosition(GridControl gridControl)
        {
            if (gridControl?.MainView is GridView gridView && GridScrollPosition != Point.Empty)
            {
                try
                {
                    gridView.TopRowIndex = GridScrollPosition.Y;
                    gridView.LeftCoord = GridScrollPosition.X;
                }
                catch
                {
                    // 如果恢复位置失败（比如数据行数变化），忽略错误
                }
            }
        }

        #endregion

        #region ActionPlan
        private int apCondition;
        private void Write2GvActionPlan(DataTable dt)
        {
            gvActionPlan.BeginDataUpdate();
            gcActionPlan.DataSource = dt;
            gvActionPlan.OptionsView.ShowIndicator = false;
            //gvDeviation.PopulateColumns();  // 确保生成列

            gvActionPlan.Columns.Clear(); // 不要清除列，否则后面代码会出错

            gvActionPlan.Columns.AddVisible("ID", "No.");
            gvActionPlan.Columns.AddVisible("DateTime", "Date");
            gvActionPlan.Columns.AddVisible("提出部门", "Assigned by");
            gvActionPlan.Columns.AddVisible("TopicINFO", "Topic");
            gvActionPlan.Columns.AddVisible("RootCause", "Root cause");
            gvActionPlan.Columns.AddVisible("Now_Action", "Action");
            gvActionPlan.Columns.AddVisible("负责部门", "Res. department");
            gvActionPlan.Columns.AddVisible("负责人姓名", "Res. person");
            gvActionPlan.Columns.AddVisible("DueDate", "Due on");
            gvActionPlan.Columns.AddVisible("Status", "Status");

            //设置文本列不可编辑
            gvActionPlan.Columns["ID"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["DateTime"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["提出部门"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["TopicINFO"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["RootCause"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["Now_Action"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["负责部门"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["负责人姓名"].OptionsColumn.AllowEdit = false;
            gvActionPlan.Columns["DueDate"].OptionsColumn.AllowEdit = true;
            gvActionPlan.Columns["Status"].OptionsColumn.AllowEdit = true;  // 让图片列可编辑

            // 配置日期列
            var repositoryItemDateEdit = new DevExpress.XtraEditors.Repository.RepositoryItemDateEdit();
            repositoryItemDateEdit.CalendarTimeProperties.DisplayFormat.FormatString = "yyyy-MM-dd";
            repositoryItemDateEdit.CalendarTimeProperties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            repositoryItemDateEdit.Mask.EditMask = "yyyy-MM-dd";
            repositoryItemDateEdit.Mask.UseMaskAsDisplayFormat = true;

            // 确保不重复添加 RepositoryItem
            if (!gcActionPlan.RepositoryItems.Contains(repositoryItemDateEdit))
            {
                gcActionPlan.RepositoryItems.Add(repositoryItemDateEdit);
            }

            // 创建 ImageComboBoxEdit
            var repositoryItemImageComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox();

            // 添加预设图片
            ImageList imageList = new ImageList();
            imageList.Images.Add("image3", Properties.Resources.进度0);
            imageList.Images.Add("image3", Properties.Resources.进度25);
            imageList.Images.Add("image3", Properties.Resources.进度50);
            imageList.Images.Add("image3", Properties.Resources.进度75);
            imageList.Images.Add("image3", Properties.Resources.进度100);

            // 绑定图片到 ImageComboBoxEdit
            repositoryItemImageComboBox.SmallImages = imageList;
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 0%", 1, 0));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 25%", 2, 1));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 50%", 3, 2));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 75%", 4, 3));
            repositoryItemImageComboBox.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("进度 100%", 5, 4));


            gvActionPlan.Columns["Status"].ColumnEdit = repositoryItemImageComboBox;
            // 确保不重复添加 RepositoryItem
            if (!gcActionPlan.RepositoryItems.Contains(repositoryItemImageComboBox))
            {
                gcActionPlan.RepositoryItems.Add(repositoryItemImageComboBox);
            }


            // 正确设置列宽（使用真实列名）
            //gvActionPlan.Columns["isConfirmation"].Width = 50;
            gvActionPlan.Columns["ID"].Width = 80;
            gvActionPlan.Columns["DateTime"].Width = 100;
            gvActionPlan.Columns["提出部门"].Width = 128;
            gvActionPlan.Columns["TopicINFO"].Width = 380;
            gvActionPlan.Columns["RootCause"].Width = 357;
            gvActionPlan.Columns["Now_Action"].Width = 380;
            gvActionPlan.Columns["负责部门"].Width = 128;
            gvActionPlan.Columns["负责人姓名"].Width = 120;
            gvActionPlan.Columns["DueDate"].Width = 100;
            gvActionPlan.Columns["Status"].Width = 110;

            //设置字体
            gvActionPlan.Appearance.Row.Font = new Font("Tahoma", 12, FontStyle.Regular);
            gvActionPlan.Appearance.HeaderPanel.Font = new Font("Tahoma", 12, FontStyle.Bold);
            gvActionPlan.Appearance.HeaderPanel.BackColor = Color.FromArgb(30, 42, 99);
            gvActionPlan.Appearance.HeaderPanel.ForeColor = Color.FromArgb(0, 0, 0);

            //设置自动换行
            // 允许行高自动调整
            gvActionPlan.OptionsView.RowAutoHeight = true;

            // 让所有行都能换行
            gvActionPlan.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

            // 让特定列换行
            gvActionPlan.Columns["TopicINFO"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvActionPlan.Columns["RootCause"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvActionPlan.Columns["Now_Action"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvActionPlan.Columns["提出部门"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvActionPlan.Columns["负责部门"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            gvActionPlan.Columns["负责人姓名"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

            // 让单元格可以输入多行文本
            var memoEdit = new DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit();
            gvActionPlan.Columns["TopicINFO"].ColumnEdit = memoEdit;
            gvActionPlan.Columns["RootCause"].ColumnEdit = memoEdit;
            gvActionPlan.Columns["Now_Action"].ColumnEdit = memoEdit;
            gvActionPlan.Columns["提出部门"].ColumnEdit = memoEdit;
            gvActionPlan.Columns["负责部门"].ColumnEdit = memoEdit;
            gvActionPlan.Columns["负责人姓名"].ColumnEdit = memoEdit;

            // 确保 RepositoryItem 绑定到 GridControl
            if (!gcActionPlan.RepositoryItems.Contains(memoEdit))
            {
                gcActionPlan.RepositoryItems.Add(memoEdit);
            }
            gvActionPlan.EndDataUpdate();
        }

        private void Search_ActionPlan(int apCondition)
        {
            if (SystemInfo.readLevel == maxDepLv)
            {
                string Condition = $"isActionPlan = 1  order by DateTime desc";//and Curr_level = {SystemInfo.readLevel} or Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel}

                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query = $"ID in ({string.Join(",", apIDs)})";
                    DataTable apdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_ActionPlan", query);

                    DataTable apActive = publicFunc.SelectedDatatable(apdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    DataTable apOverdue = publicFunc.SelectedDatatable(apdata, $"DueDate < '{DateTime.Now.Date}'  and Done_tag = 0");
                    DataTable apDone = publicFunc.SelectedDatatable(apdata, $"Done_tag = 1");

                    lbAPaction.Text = apActive.Rows.Count.ToString();
                    lbAPoverdue.Text = apOverdue.Rows.Count.ToString();
                    lbAPdone.Text = apDone.Rows.Count.ToString();

                    //Write2GvActionPlan(apdata);
                    switch (apCondition)
                    {
                        //选择active
                        case 0:
                            Write2GvActionPlan(apActive);
                            break;
                        //选择active
                        case 1:
                            Write2GvActionPlan(apOverdue);
                            break;
                        case 2:
                            Write2GvActionPlan(apDone);
                            break;
                        default:
                            break;
                    }
                }
            }
            else
            {
                //2025-1-23 修改筛选部门筛选当前等级部门及当前等级部门一下的升级上来的问题
                DataTable depSelect = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");

                string depments = SystemInfo.readparentDep.ToString();
                for (int i = 0; i < depSelect.Rows.Count; i++)
                {
                    depments = depments + $",{depSelect.Rows[i][0].ToString()}";
                }
                string Condition = $"isActionPlan = 1 and (提出部门ID in ({depments}) or 负责部门ID in ({depments})) and Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel}) order by DateTime desc";
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < apIDs.Length; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query = $"ID in ({string.Join(",", apIDs)})";
                    DataTable apdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_ActionPlan", query);

                    DataTable apActive = publicFunc.SelectedDatatable(apdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    DataTable apOverdue = publicFunc.SelectedDatatable(apdata, $"DueDate < '{DateTime.Now.Date}'  and Done_tag = 0");
                    DataTable apDone = publicFunc.SelectedDatatable(apdata, $"Done_tag = 1");

                    lbAPaction.Text = apActive.Rows.Count.ToString();
                    lbAPoverdue.Text = apOverdue.Rows.Count.ToString();
                    lbAPdone.Text = apDone.Rows.Count.ToString();

                    //Write2GvActionPlan(apdata);
                    switch (apCondition)
                    {
                        //选择active
                        case 0:
                            Write2GvActionPlan(apActive);
                            break;
                        //选择active
                        case 1:
                            Write2GvActionPlan(apOverdue);
                            break;
                        case 2:
                            Write2GvActionPlan(apDone);
                            break;
                        default:
                            break;
                    }
                }

            }
        }

        private void lbAPaction_Click(object sender, EventArgs e)
        {
            apCondition = 0;
            Search_ActionPlan(apCondition);
            plAPaction.BackColor = Color.LimeGreen;
            plAPoverdue.BackColor = Color.Transparent;
            plAPdone.BackColor = Color.Transparent;
            //gvActionPlan.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序

        }

        private void lbAPoverdue_Click(object sender, EventArgs e)
        {
            apCondition = 1;
            Search_ActionPlan(apCondition);
            plAPaction.BackColor = Color.Transparent;
            plAPoverdue.BackColor = Color.LimeGreen;
            plAPdone.BackColor = Color.Transparent;
            if (gvActionPlan.Columns.Count > 0 && gvActionPlan.RowCount > 0)
            {
                gvActionPlan.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序
            }

        }

        private void lbAPdone_Click(object sender, EventArgs e)
        {
            apCondition = 2;
            Search_ActionPlan(apCondition);
            plAPaction.BackColor = Color.Transparent;
            plAPoverdue.BackColor = Color.Transparent;
            plAPdone.BackColor = Color.LimeGreen;
            gvActionPlan.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序
        }

        private void btnAPdone_Click(object sender, EventArgs e)
        {
            if (apRowIndex != -1)
            {
                int apID = Convert.ToInt32(gvActionPlan.GetRowCellValue(apRowIndex, "ID"));
                bool res = SQL.Update(SystemInfo.SQL, "ActionPlan", "Done_tag = 1", $"Todo_ID = {apID}");
                if (res)
                {
                    XtraMessageBox.Show("完成更改！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //重新载入
                    apRowIndex = -1;
                    Search_ActionPlan(apCondition);
                }
            }
        }
        private int apRowIndex = -1;
        private void gvActionPlan_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    apRowIndex = hitInfo.RowHandle;
                }
            }

        }
        #endregion

        #region Feed back
        private int fbCondition;

        private void Search_Feedback(int fdCondition)
        {
            if (SystemInfo.readLevel == maxDepLv)
            {
                string Condition = $"isFeedback = 1 and Curr_level = {SystemInfo.readLevel} or Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel} order by ID desc";

                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query = $"ID in ({string.Join(",", apIDs)})";
                    DataTable fbdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Feedback", query);

                    DataTable fbActive = publicFunc.SelectedDatatable(fbdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    DataTable fbOverdue = publicFunc.SelectedDatatable(fbdata, $"DueDate < '{DateTime.Now.Date}'  and Done_tag = 0");
                    DataTable fbDone = publicFunc.SelectedDatatable(fbdata, $"Done_tag = 1");

                    lbFBactive.Text = fbActive.Rows.Count.ToString();
                    lbFBoverdue.Text = fbOverdue.Rows.Count.ToString();
                    lbFBdone.Text = fbDone.Rows.Count.ToString();

                    switch (fdCondition)
                    {
                        //选择active
                        case 0:
                            publicFunc.Write2Gridview(fbActive, gcFeedback, gvFeedback);
                            break;
                        //选择active
                        case 1:
                            publicFunc.Write2Gridview(fbOverdue, gcFeedback, gvFeedback);
                            break;
                        case 2:
                            publicFunc.Write2Gridview(fbDone, gcFeedback, gvFeedback);
                            break;
                        default:
                            break;
                    }
                }
            }
            else
            {
                //2025-1-23 修改筛选部门筛选当前等级部门及当前等级部门一下的升级上来的问题
                string query1 = $@"
-- 假设要查询ID为1的部门的所有子部门
DECLARE @DepartmentID int = {SystemInfo.readparentDep};

WITH DepartmentHierarchy AS (
    -- 基础查询
    SELECT 
        ID,
        DepartmentName,
        ParentDepartmentID,
        departmentLevel,
        1 as Level,
        CAST(DepartmentName as nvarchar(1000)) as Path
    FROM Departments
    WHERE ParentDepartmentID =  @DepartmentID and Del_tag = 0
    
    UNION ALL
    
    -- 递归部分
    SELECT 
        d.ID,
        d.DepartmentName,
        d.ParentDepartmentID,
        d.departmentLevel,
        dh.Level + 1,
        CAST(dh.Path + ' > ' + d.DepartmentName as nvarchar(1000))
    FROM Departments d
    INNER JOIN DepartmentHierarchy dh ON d.ParentDepartmentID = dh.ID
    WHERE d.Del_tag = 0
)
SELECT 
    ID,
    DepartmentName,
    ParentDepartmentID,
    departmentLevel,
    Level as HierarchyLevel,
    Path as DepartmentPath
FROM DepartmentHierarchy
ORDER BY Level, ID;";
                //DataTable depSelect = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");
                DataTable depSelect = SQL.ReturnDataTable(SystemInfo.SQL, query1);

                string depments = SystemInfo.readparentDep.ToString();
                for (int i = 0; i < depSelect.Rows.Count; i++)
                {
                    depments = depments + $",{depSelect.Rows[i][0].ToString()}";
                }
                string Condition = $"isFeedback = 1 and (提出部门ID in ({depments}) or 负责部门ID in ({depments}))  order by ID desc";//and Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel})
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < apIDs.Length; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query = $"ID in ({string.Join(",", apIDs)})";
                    DataTable fbdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Feedback", query);

                    DataTable fbActive = publicFunc.SelectedDatatable(fbdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    DataTable fbOverdue = publicFunc.SelectedDatatable(fbdata, $"DueDate < '{DateTime.Now.Date}'  and Done_tag = 0");
                    DataTable fbDone = publicFunc.SelectedDatatable(fbdata, $"Done_tag = 1");

                    lbFBactive.Text = fbActive.Rows.Count.ToString();
                    lbFBoverdue.Text = fbOverdue.Rows.Count.ToString();
                    lbFBdone.Text = fbDone.Rows.Count.ToString();

                    switch (fbCondition)
                    {
                        //选择active
                        case 0:
                            publicFunc.Write2Gridview(fbActive, gcFeedback, gvFeedback);
                            break;
                        //选择active
                        case 1:
                            publicFunc.Write2Gridview(fbOverdue, gcFeedback, gvFeedback);
                            break;
                        case 2:
                            publicFunc.Write2Gridview(fbDone, gcFeedback, gvFeedback);
                            break;
                        default:
                            break;
                    }
                }

            }
        }

        private void lbFBactive_Click(object sender, EventArgs e)
        {
            fbCondition = 0;
            Search_Feedback(fbCondition);
            plFDactive.BackColor = Color.LimeGreen;
            plFDoverdue.BackColor = Color.Transparent;
            plFDdone.BackColor = Color.Transparent;
            if (gvFeedback.Columns.Count > 0)
            {
                gvFeedback.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序
            }
            //
        }

        private void lbFBoverdue_Click(object sender, EventArgs e)
        {
            fbCondition = 1;
            Search_Feedback(fbCondition);
            plFDactive.BackColor = Color.Transparent;
            plFDoverdue.BackColor = Color.LimeGreen;
            plFDdone.BackColor = Color.Transparent;
            if (gvFeedback.Columns.Count > 0 && gvFeedback.RowCount > 0)
            {
                gvFeedback.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序

            }

        }

        private void lbFBdone_Click(object sender, EventArgs e)
        {
            fbCondition = 2;
            Search_Feedback(fbCondition);
            plFDactive.BackColor = Color.Transparent;
            plFDoverdue.BackColor = Color.Transparent;
            plFDdone.BackColor = Color.LimeGreen;
            if (gvFeedback.Columns.Count > 0 && gvFeedback.RowCount > 0)
            {
                gvFeedback.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序

            }

        }

        private void btnFeedbackDone_Click(object sender, EventArgs e)
        {
            if (fbRowIndex != -1)
            {
                int apID = Convert.ToInt32(gvFeedback.GetRowCellValue(fbRowIndex, "ID"));
                bool res = SQL.Update(SystemInfo.SQL, "Feedback", "Done_tag = 1", $"Todo_ID = {apID}");
                if (res)
                {
                    XtraMessageBox.Show("完成更改！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //重新载入
                    fbRowIndex = -1;
                    Search_Feedback(fbCondition);
                }
            }
        }
        private int fbRowIndex = -1;
        private void gvFeedback_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    fbRowIndex = hitInfo.RowHandle;
                }
            }
        }

        #endregion

        #region Go & See
        private int gsCondition;
        private void Search_Gosee(int gsCondition)
        {
            if (SystemInfo.readLevel == maxDepLv)
            {
                string Condition = $"isGoSee = 1 and Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel}) order by ID desc";//

                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query = $"ID in ({string.Join(",", apIDs)})";
                    DataTable gsdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Gosee", query);

                    DataTable gsActive = publicFunc.SelectedDatatable(gsdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    DataTable gsOverdue = publicFunc.SelectedDatatable(gsdata, $"DueDate < '{DateTime.Now.Date}'  and Done_tag = 0");
                    DataTable gsDone = publicFunc.SelectedDatatable(gsdata, $"Done_tag = 1");

                    lbGSactive.Text = gsActive.Rows.Count.ToString();
                    lbGSoverdue.Text = gsOverdue.Rows.Count.ToString();
                    lbGSdone.Text = gsDone.Rows.Count.ToString();

                    //Write2GvActionPlan(apdata);
                    switch (gsCondition)
                    {
                        //选择active
                        case 0:
                            publicFunc.Write2Gridview(gsActive, gcGosee, gvGosee);
                            break;
                        //选择active
                        case 1:
                            publicFunc.Write2Gridview(gsOverdue, gcGosee, gvGosee);
                            break;
                        case 2:
                            publicFunc.Write2Gridview(gsDone, gcGosee, gvGosee);
                            break;
                        default:
                            break;
                    }
                }
            }
            else
            {
                //2025-1-23 修改筛选部门筛选当前等级部门及当前等级部门一下的升级上来的问题
                DataTable depSelect = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");

                string depments = SystemInfo.readparentDep.ToString();
                for (int i = 0; i < depSelect.Rows.Count; i++)
                {
                    depments = depments + $",{depSelect.Rows[i][0].ToString()}";
                }
                string Condition = $"isGoSee = 1  order by ID desc";//and (提出部门ID in ({depments}) or 负责部门ID in ({depments})) and Curr_level = {SystemInfo.readLevel} or (Curr_level <= {SystemInfo.readLevel} and isUpdate = {SystemInfo.readLevel})
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", Condition);
                if (dt.Rows.Count > 0)
                {
                    int[] apIDs = new int[dt.Rows.Count];
                    for (int i = 0; i < apIDs.Length; i++)
                    {
                        apIDs[i] = (int)dt.Rows[i]["ID"];
                    }
                    string query = $"ID in ({string.Join(",", apIDs)})";
                    DataTable gsdata = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Gosee", query);

                    DataTable gsActive = publicFunc.SelectedDatatable(gsdata, $"DueDate >= '{DateTime.Now.Date}' and Done_tag = 0");
                    DataTable gsOverdue = publicFunc.SelectedDatatable(gsdata, $"DueDate < '{DateTime.Now.Date}'  and Done_tag = 0");
                    DataTable gsDone = publicFunc.SelectedDatatable(gsdata, $"Done_tag = 1");

                    lbGSactive.Text = gsActive.Rows.Count.ToString();
                    lbGSoverdue.Text = gsOverdue.Rows.Count.ToString();
                    lbGSdone.Text = gsDone.Rows.Count.ToString();

                    //Write2GvActionPlan(apdata);
                    switch (gsCondition)
                    {
                        //选择active
                        case 0:
                            publicFunc.Write2Gridview(gsActive, gcGosee, gvGosee);
                            break;
                        //选择active
                        case 1:
                            publicFunc.Write2Gridview(gsOverdue, gcGosee, gvGosee);
                            break;
                        case 2:
                            publicFunc.Write2Gridview(gsDone, gcGosee, gvGosee);
                            break;
                        default:
                            break;
                    }
                }

            }
        }

        private void lbGSactive_Click(object sender, EventArgs e)
        {
            gsCondition = 0;
            Search_Gosee(gsCondition);
            plGSactive.BackColor = Color.LimeGreen;
            plGSoverdue.BackColor = Color.Transparent;
            plGSdone.BackColor = Color.Transparent;
            if (gvGosee.Columns.Count > 0 && gvGosee.RowCount > 0)
            {
                gvGosee.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序
            }


        }

        private void lbGSoverdue_Click(object sender, EventArgs e)
        {
            gsCondition = 1;
            Search_Gosee(gsCondition);
            plGSactive.BackColor = Color.Transparent;
            plGSoverdue.BackColor = Color.LimeGreen;
            plGSdone.BackColor = Color.Transparent;
            if (gvGosee.Columns.Count > 0)
                if (gvGosee.Columns.Count > 0 && gvGosee.RowCount > 0)
                {
                    gvGosee.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序
                }

        }

        private void lbGSdone_Click(object sender, EventArgs e)
        {
            gsCondition = 2;
            Search_Gosee(gsCondition);
            plGSactive.BackColor = Color.Transparent;
            plGSoverdue.BackColor = Color.Transparent;
            plGSdone.BackColor = Color.LimeGreen;
            if (gvGosee.Columns.Count > 0 && gvGosee.RowCount > 0)
            {
                gvGosee.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;  // 日期降序
            }

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (gsRowIndex != -1)
            {
                int apID = Convert.ToInt32(gvGosee.GetRowCellValue(gsRowIndex, "ID"));
                bool res = SQL.Update(SystemInfo.SQL, "GoSee", "Done_tag = 1", $"Todo_ID = {apID}");
                if (res)
                {
                    XtraMessageBox.Show("完成更改！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //重新载入
                    gsRowIndex = 0;
                    Search_Gosee(gsCondition);
                }
            }
        }
        private int gsRowIndex = 0;
        private void gvGosee_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    gsRowIndex = hitInfo.RowHandle;
                }
            }
        }
        #endregion

        #region 系统设置
        private void btnSettings_Click(object sender, EventArgs e)
        {
            //MessageBox.Show($"readFactory = {SystemInfo.readFactory}\nreadLevel = {SystemInfo.readLevel}\nreadParent = {SystemInfo.readparentDep}\nreadDepartment = {SystemInfo.readDepartment}\nfac = {Properties.Settings.Default.Factory}");

            sysSettings.instance = new sysSettings();
            sysSettings.instance.ShowDialog();
            //sysSettings.instance.ShowDialog();
            //MessageBox.Show($"{gvDeviation.Columns["TopicINFO"].Width}，{gvDeviation.Columns["TodoINFO"].Width},{gvDeviation.Columns["RootCause"].Width},{gvDeviation.Columns["提出部门"].Width}");
        }

        private void DevMainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
        private void StartSqlDependency()
        {
            SqlDependency.Start(SystemInfo.SQL);
            LoadDeviationWithDependency();
        }

        private void LoadDeviationWithDependency()
        {
            using (SqlConnection conn = new SqlConnection(SystemInfo.SQL))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM View_Todo", conn);
                SqlDependency dep = new SqlDependency(cmd);
                dep.OnChange += new OnChangeEventHandler(Dependency_OnChange);
                cmd.ExecuteReader();
            }
        }

        private void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                // 数据库数据变化时自动刷新 GridView
                this.Invoke(new Action(() => LoadDeviation(timeCondition)));
            }
        }


        #endregion

        #region Top issue
        private int topCondition;
        private int issueRowIndex = -1;

        // Top Issue GridControl 状态保存变量
        private Dictionary<string, DevExpress.Data.ColumnSortOrder> currentTopIssueSortInfo;
        private int currentTopIssueTopRowIndex;
        private int currentTopIssueLeftCoord;
        private object currentTopIssueFocusedRowKey;
        private Dictionary<string, int> currentTopIssueColumnWidths;
        private string[] hiddenTopIssueColumns = { "ID", "Level", "From_DepartmentID", "Update" };

        private void gvTopissue_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    issueRowIndex = hitInfo.RowHandle;
                    //MessageBox.Show(issueRowIndex.ToString());
                }
            }

        }
        private void LoadinTopissue()
        {
            //初始化按键图片
            publicFunc.Init_ImageInButton(btnTop1, Properties.Resources.top1右);
            publicFunc.Init_ImageInButton(btnTop2, Properties.Resources.top2右);
            publicFunc.Init_ImageInButton(btnTop3, Properties.Resources.top3右);

            //

        }

        private void Write2GridViewTopIssue(DataTable dt, string idArray)
        {
            // 保存当前网格状态
            SaveCurrentTopIssueGridState();

            gvTopissue.BeginDataUpdate();
            gcTopissue.DataSource = dt;

            DataTable tpActive = publicFunc.SelectedDatatable(dt, $"DateTime >= '{DateTime.Now.AddDays(-1).Date}' and Complete = 0");
            DataTable tpTotal = publicFunc.SelectedDatatable(dt, $"Complete = 0 and From_DepartmentID = {SystemInfo.readparentDep}");
            DataTable tpDone = publicFunc.SelectedDatatable(dt, $"Complete = 1 and From_DepartmentID = {SystemInfo.readparentDep}");

            lbTopActive.Text = tpActive.Rows.Count.ToString();
            lbTopTotal.Text = tpTotal.Rows.Count.ToString();
            lbTopDone.Text = tpDone.Rows.Count.ToString();

            switch (topCondition)
            {
                case 0:
                    gcTopissue.DataSource = tpActive;
                    break;
                case 1:
                    gcTopissue.DataSource = tpTotal;
                    break;
                case 2:
                    gcTopissue.DataSource = tpDone;
                    break;
            }
            //gvTopissue.Columns["DateTime"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            //gvTopissue.Columns["DateTime"].DisplayFormat.FormatString = "yyyy-MM-dd"; // 自定义日期时间格式

            // 隐藏指定列
            HideSpecifiedTopIssueColumns();
            gvTopissue.Columns["ID"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["Complete"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["DateTime"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["Topic"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["Department"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["Level"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["Escalation"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["CIP"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["Employee name"].OptionsColumn.AllowEdit = false;
            gvTopissue.Columns["IncompleteTodoCount"].OptionsColumn.AllowEdit = false;

            gvTopissue.Columns["Complete"].Width = 80;
            gvTopissue.Columns["DateTime"].Width = 80;
            gvTopissue.Columns["DateTime"].Caption = "Date time";
            gvTopissue.Columns["Department"].Width = 128;
            gvTopissue.Columns["Topic"].Width = 627;
            gvTopissue.Columns["Level"].Width = 100;
            gvTopissue.Columns["Escalation"].Width = 80;
            gvTopissue.Columns["CIP"].Width = 50;
            gvTopissue.Columns["Employee name"].Width = 120;
            gvTopissue.Columns["Employee name"].Caption = "Person";


            gvTopissue.Columns["Complete"].Caption = "";
            gvTopissue.Columns["DateTime"].Caption = "Date";
            gvTopissue.Columns["Department"].Caption = "Department";
            gvTopissue.Columns["Topic"].Caption = "Topic";
            gvTopissue.Columns["Level"].Caption = "Level";
            gvTopissue.Columns["Escalation"].Caption = "Escalation";
            gvTopissue.Columns["CIP"].Caption = "CIP";
            gvTopissue.Columns["Employee name"].Caption = "Person";
            gvTopissue.Columns["IncompleteTodoCount"].Width = 100;
            gvTopissue.Columns["IncompleteTodoCount"].Caption = "Incomplete todo";

            gvTopissue.Appearance.Row.Font = new Font("Tahoma", 12);
            gvTopissue.Appearance.HeaderPanel.Font = new Font("Tahoma", 12, FontStyle.Bold);
            // 允许行高自动调整
            gvTopissue.OptionsView.RowAutoHeight = true;

            // 让所有行都能换行
            gvTopissue.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;// 让特定列换行
            gvTopissue.Columns["Topic"].AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;

            // 让单元格可以输入多行文本
            var memoEdit = new DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit();
            gvTopissue.Columns["Topic"].ColumnEdit = memoEdit;

            gvTopissue.EndDataUpdate();

            // 恢复网格状态
            RestoreTopIssueGridState();
        }

        /// <summary>
        /// 保存当前 Top Issue GridControl 的状态
        /// </summary>
        private void SaveCurrentTopIssueGridState()
        {
            if (gvTopissue.Columns.Count == 0) return;

            try
            {
                // 保存排序信息
                currentTopIssueSortInfo = new Dictionary<string, DevExpress.Data.ColumnSortOrder>();
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gvTopissue.Columns)
                {
                    if (column.SortOrder != DevExpress.Data.ColumnSortOrder.None)
                    {
                        currentTopIssueSortInfo[column.FieldName] = column.SortOrder;
                    }
                }

                // 保存滚动位置
                currentTopIssueTopRowIndex = gvTopissue.TopRowIndex;
                currentTopIssueLeftCoord = gvTopissue.LeftCoord;

                // 保存焦点行
                if (gvTopissue.FocusedRowHandle >= 0)
                {
                    currentTopIssueFocusedRowKey = gvTopissue.GetRowCellValue(gvTopissue.FocusedRowHandle, gvTopissue.Columns[0]);
                }

                // 保存列宽
                currentTopIssueColumnWidths = new Dictionary<string, int>();
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gvTopissue.Columns)
                {
                    currentTopIssueColumnWidths[column.FieldName] = column.Width;
                }
            }
            catch
            {
                // 忽略保存状态时的错误
            }
        }

        /// <summary>
        /// 恢复 Top Issue GridControl 的状态
        /// </summary>
        private void RestoreTopIssueGridState()
        {
            if (gvTopissue.Columns.Count == 0) return;

            try
            {
                // 恢复列宽
                if (currentTopIssueColumnWidths != null)
                {
                    foreach (DevExpress.XtraGrid.Columns.GridColumn column in gvTopissue.Columns)
                    {
                        if (currentTopIssueColumnWidths.ContainsKey(column.FieldName))
                        {
                            column.Width = currentTopIssueColumnWidths[column.FieldName];
                        }
                    }
                }

                // 恢复排序信息
                if (currentTopIssueSortInfo != null && currentTopIssueSortInfo.Count > 0)
                {
                    foreach (DevExpress.XtraGrid.Columns.GridColumn column in gvTopissue.Columns)
                    {
                        if (currentTopIssueSortInfo.ContainsKey(column.FieldName))
                        {
                            column.SortOrder = currentTopIssueSortInfo[column.FieldName];
                        }
                    }
                }
                else
                {
                    // 如果没有保存的排序信息，设置默认排序
                    if (gvTopissue.Columns["DateTime"] != null)
                    {
                        gvTopissue.Columns["DateTime"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
                    }
                }

                // 延迟恢复滚动位置和焦点行
                System.Windows.Forms.Application.DoEvents();

                // 恢复滚动位置
                if (currentTopIssueTopRowIndex >= 0)
                {
                    gvTopissue.TopRowIndex = currentTopIssueTopRowIndex;
                }
                if (currentTopIssueLeftCoord >= 0)
                {
                    gvTopissue.LeftCoord = currentTopIssueLeftCoord;
                }

                // 恢复焦点行
                if (currentTopIssueFocusedRowKey != null)
                {
                    for (int i = 0; i < gvTopissue.RowCount; i++)
                    {
                        if (gvTopissue.GetRowCellValue(i, gvTopissue.Columns[0])?.Equals(currentTopIssueFocusedRowKey) == true)
                        {
                            gvTopissue.FocusedRowHandle = i;
                            break;
                        }
                    }
                }
            }
            catch
            {
                // 忽略恢复状态时的错误
            }
        }

        /// <summary>
        /// 隐藏指定的 Top Issue 列
        /// </summary>
        private void HideSpecifiedTopIssueColumns()
        {
            try
            {
                foreach (string columnName in hiddenTopIssueColumns)
                {
                    if (gvTopissue.Columns[columnName] != null)
                    {
                        gvTopissue.Columns[columnName].Visible = false;
                    }
                }
            }
            catch
            {
                // 忽略隐藏列时的错误
            }
        }

        private void Search_Topissue()
        {
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ID = {SystemInfo.readparentDep} or ParentDepartmentID = {SystemInfo.readparentDep}");
            DataTable dtSlave = SQL.ReturnDataTable3(SystemInfo.SQL, "DepRelation", $"mainDepID = {SystemInfo.readparentDep} and Del_tag = 0 and isConfirm = 1 and isSQDC = 1 and isTopic = 1");
            int[] ids = new int[dt.Rows.Count + 1];
            int[] ids2 = new int[dtSlave.Rows.Count + 1];
            ids[0] = SystemInfo.readparentDep;
            ids2[0] = SystemInfo.readparentDep;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ids[i + 1] = (int)dt.Rows[i]["ID"];
                }
            }
            if (dtSlave.Rows.Count > 0)
            {
                for (int i = 0; i < dtSlave.Rows.Count; i++)
                {
                    ids2[i + 1] = (int)dtSlave.Rows[i]["DepID"];
                }
            }
            string idArray = string.Join(",", ids);
            string idArray2 = string.Join(",", ids2);
            string queryTp = $@"
WITH TopTopics AS ( 
    SELECT TopicID, MIN(DepartmentID) AS DepartmentID  -- 或者使用MAX，根据业务需求
    FROM (
        SELECT Top1ID AS TopicID, DepartmentID 
        FROM Top_Issue_Tag 
        WHERE DepartmentID IN ({idArray + "," + idArray2}) 
        AND Top1ID IS NOT NULL
        
        UNION ALL 
        SELECT Top2ID AS TopicID, DepartmentID 
        FROM Top_Issue_Tag 
        WHERE DepartmentID IN ({idArray + "," + idArray2}) 
        AND Top2ID IS NOT NULL
        
        UNION ALL 
        SELECT Top3ID AS TopicID, DepartmentID 
        FROM Top_Issue_Tag 
        WHERE DepartmentID IN ({idArray + "," + idArray2}) 
        AND Top3ID IS NOT NULL
    ) AS AllTopics
    GROUP BY TopicID
) 
SELECT 
    vt.ID, 
    vt.isComplete AS Complete, 
    vt.DateTime, 
    vt.TopicINFO AS Topic, 
    vt.Department, 
    vt.FullName AS [Employee name], 
    vt.isEscalation AS Escalation, 
    vt.isCIP AS CIP, 
    vt.Level_tag AS [Level], 
    vt.isUpdate AS [Update], 
    ISNULL(todocount.IncompleteTodoCount, 0) AS IncompleteTodoCount, 
    top_topics.DepartmentID AS [From_DepartmentID]
FROM TopTopics top_topics 
INNER JOIN View_Topic vt ON vt.ID = top_topics.TopicID AND (vt.Level_tag = 'L{SystemInfo.readLevel}' OR vt.isUpdate = {SystemInfo.readLevel}) 
LEFT JOIN ( 
    SELECT 
        TopicID, 
        COUNT(*) AS IncompleteTodoCount 
    FROM Todo 
    WHERE isConfirmation = 0 
    GROUP BY TopicID 
) AS todocount ON vt.ID = todocount.TopicID
";

            DataTable dtTop = SQL.ReturnDataTable(SystemInfo.SQL, queryTp);
            Write2GridViewTopIssue(dtTop, idArray);


        }
        private void lbTopActive_Click(object sender, EventArgs e)
        {
            topCondition = 0;
            Search_Topissue();

            plTopActive.BackColor = Color.LimeGreen;
            plTopTotal.BackColor = Color.Transparent;
            plTopDone.BackColor = Color.Transparent;
        }

        private void lbTopTotal_Click(object sender, EventArgs e)
        {
            topCondition = 1;
            Search_Topissue();

            plTopActive.BackColor = Color.Transparent;
            plTopTotal.BackColor = Color.LimeGreen;
            plTopDone.BackColor = Color.Transparent;
        }

        private void SetTopInTPpage(int i)
        {
            int topicID = Convert.ToInt32(gvTopissue.GetRowCellValue(issueRowIndex, "ID"));
            if (publicFunc.GetUserScope(SystemInfo.userID, SystemInfo.readparentDep) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }

            //查询今天的Top issue里有没有数据
            DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Top_Issue_Tag", $"Date = '{DateTime.Now.Date}' and DepartmentID = {SystemInfo.readparentDep}");
            if (dt.Rows.Count > 0)
            {
                //查询是否一下是否在今天Top中，如果是提醒用户是否重新定义

                bool res = SQL.Update(SystemInfo.SQL, "Top_Issue_Tag", $"Top{i}ID = {topicID}", $"ID = {(int)dt.Rows[0]["ID"]}");
                if (res)
                {
                    bool updateTopic = SQL.Update(SystemInfo.SQL, "Topic", $"Curr_top = {i}", $"ID = {topicID}");
                    if (updateTopic)
                    {
                        //
                        XtraMessageBox.Show(LookAndFeel, $"成功设置为Top{i}");
                        issueRowIndex = -1;
                    }

                }
            }
            else
            {
                int res = SQL.InsertReturnID(SystemInfo.SQL, "Top_Issue_Tag", $"DepartmentID,Top{i}ID,Date,Create_userID,FactoryID", $"{SystemInfo.readparentDep},{topicID},'{DateTime.Now.Date}',{SystemInfo.userID},{SystemInfo.readFactory}");
                if (res > 0)
                {
                    bool updateTopic = SQL.Update(SystemInfo.SQL, "Topic", $"Curr_top = {i}", $"ID = {topicID}");
                    if (updateTopic)
                    {
                        XtraMessageBox.Show(LookAndFeel, $"成功设置为Top{i}");
                        issueRowIndex = -1;
                    }
                }
            }
        }

        private void RemoveTopInTPpage()
        {
            int topicID = Convert.ToInt32(gvTopissue.GetRowCellValue(issueRowIndex, "ID"));
            if (publicFunc.GetUserScope(SystemInfo.userID, SystemInfo.readparentDep) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }

            DataTable dtTag = SQL.ReturnDataTable3(SystemInfo.SQL, "Top_Issue_Tag", $"DepartmentID = {SystemInfo.readparentDep} and Date = '{DateTime.Now.Date}'");
            if (dtTag.Rows.Count > 0)
            {
                for (int i = 1; i <= 3; i++)
                {
                    if ((int)dtTag.Rows[0][$"Top{i}ID"] == topicID)
                    {
                        bool res = SQL.Update(SystemInfo.SQL, "Top_Issue_Tag", $"Top{i}ID = 0", $"ID = {(int)dtTag.Rows[0]["ID"]}");
                        if (res)
                        {
                            issueRowIndex = -1;
                            XtraMessageBox.Show(LookAndFeel, $"成功移除Top{i}");
                            break;
                        }
                    }

                }

            }
            else
            {
                XtraMessageBox.Show(LookAndFeel, "未被定义为Top问题");
            }
        }
        private void lbTopDone_Click(object sender, EventArgs e)
        {
            topCondition = 2;
            Search_Topissue();


            plTopActive.BackColor = Color.Transparent;
            plTopTotal.BackColor = Color.Transparent;
            plTopDone.BackColor = Color.LimeGreen;

        }
        private void btnTop1_Click(object sender, EventArgs e)
        {
            SetTopInTPpage(1);
        }

        private void btnTop2_Click(object sender, EventArgs e)
        {
            SetTopInTPpage(2);

        }

        private void btnTop3_Click(object sender, EventArgs e)
        {
            SetTopInTPpage(3);
        }

        private void btnTopRemove_Click(object sender, EventArgs e)
        {
            RemoveTopInTPpage();
        }
        private void btnTopDone_Click(object sender, EventArgs e)
        {
            int todoID = Convert.ToInt32(gvTopissue.GetRowCellValue(issueRowIndex, "ID"));
            int actionUnconfirm = Convert.ToInt32(gvTopissue.GetRowCellValue(issueRowIndex, "IncompleteTodoCount"));
            if (actionUnconfirm == 0)
            {
                bool update = SQL.Update(SystemInfo.SQL, "Topic", "isComplete = 1", $"ID = {todoID}");
                issueRowIndex = -1;
                XtraMessageBox.Show(LookAndFeel, "设置成功！");
                Search_Topissue();


            }
        }
        #endregion

        #region Meeting attendance
        private void LoadMeetingInOverview()
        {
            DataTable dtMember = SQL.ReturnDataTable3(SystemInfo.SQL, "View_MeetingAttendance", $"MeetingID = {MeetingId} and Year = {DateTime.Now.Year} and Week = {attendance_input.instance.GetWeek(DateTime.Now)} order by Sort");
            mainGcMeeting.DataSource = dtMember;

            mainGvMeeting.Columns.Clear();
            mainGvMeeting.Columns.AddVisible("FullName");
            string dayOfWeek = DateTime.Now.DayOfWeek.ToString();
            mainGvMeeting.Columns.AddVisible(dayOfWeek);

            mainGvMeeting.Columns["FullName"].Caption = "Member name";

        }
        private void linkCreateMeeting_Click(object sender, EventArgs e)
        {
            //指向会议建立窗口
            meetingCreateForm.instance.ShowDialog();
        }

        public static int MeetingId;
        public void LoadMeeting()
        {
            gcMeeting.DataSource = null;
            gvMeeting.RefreshData();
            //Meetinglevel和readLevel相同
            DataTable mt = SQL.ReturnDataTable3(SystemInfo.SQL, "Meeting", $"MeetingLevel = {SystemInfo.readLevel} and MeetingDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");
            int meetingID = 0;
            MeetingId = meetingID;
            if (mt.Rows.Count > 0)
            {
                gcMeeting.Visible = true;
                meetingID = (int)mt.Rows[0]["ID"];
                MeetingId = meetingID;
                string meetingMember = mt.Rows[0]["MeetingMember"].ToString();
                int[] memberIDArray = meetingMember.Split(',')       // 按逗号分割字符串
                                                   .Select(int.Parse) // 转换为整数
                                                   .ToArray();       // 转换为 int 数组

                //获得用户列表
                DataTable dtMember = SQL.ReturnDataTable3(SystemInfo.SQL, "View_MeetingAttendance", $"MeetingID = {meetingID} and Year = {DateTime.Now.Year} and Week = {attendance_input.instance.GetWeek(DateTime.Now)} order by Sort");
                if (dtMember.Rows.Count == 0)
                {
                    for (int i = 0; i < memberIDArray.Length; i++)
                    {
                        string col = "MeetingID, MemberID, Year, Week,Sort";
                        string value = $"{meetingID}, {memberIDArray[i]}, {DateTime.Now.Year}, {attendance_input.instance.GetWeek(DateTime.Now)},{i + 1}";
                        int idx = SQL.InsertReturnID(SystemInfo.SQL, "MeetingAttendance", col, value);
                    }
                }
                DataTable dtReLoad = SQL.ReturnDataTable3(SystemInfo.SQL, "View_MeetingAttendance", $"MeetingID = {meetingID} and Year = {DateTime.Now.Year} and Week = {attendance_input.instance.GetWeek(DateTime.Now)} order by Sort");

                gcMeeting.DataSource = dtReLoad;

                gvMeeting.Columns["FullName"].OptionsColumn.AllowEdit = false;
                gvMeeting.Columns["FullName"].Caption = "Member name";
                gvMeeting.Columns["Monday"].OptionsColumn.AllowEdit = false;
                gvMeeting.Columns["Tuesday"].OptionsColumn.AllowEdit = false;
                gvMeeting.Columns["Wednesday"].OptionsColumn.AllowEdit = false;
                gvMeeting.Columns["Thursday"].OptionsColumn.AllowEdit = false;
                gvMeeting.Columns["Friday"].OptionsColumn.AllowEdit = false;
                gvMeeting.Columns["Saturday"].OptionsColumn.AllowEdit = false;
                gvMeeting.Columns["Sunday"].OptionsColumn.AllowEdit = false;

                gvMeeting.Columns["MeetingID"].Visible = false;
                gvMeeting.Columns["MemberID"].Visible = false;
                gvMeeting.Columns["Year"].Visible = false;
                gvMeeting.Columns["Week"].Visible = false;
                gvMeeting.Columns["Sort"].Visible = false;



            }
            else
            {
                gcMeeting.Visible = false;
            }

            gvMeeting.Appearance.Row.Font = new Font("Tahoma", 14);
            gvMeeting.Appearance.HeaderPanel.Font = new Font("Tahoma", 14, FontStyle.Bold);

        }

        private void btnAttandence_Click(object sender, EventArgs e)
        {
            attendance_input.instance.ShowDialog();
        }

        private void btnMeetingSettings_Click(object sender, EventArgs e)
        {
            if (publicFunc.GetUserScope(SystemInfo.userID, SystemInfo.readparentDep) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            meetingCreateForm.instance.ShowDialog();
        }
        #endregion

        #region Root cause
        public static string A3number;

        private void GridView1_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle < 0) return;

            for (int i = 1; i <= 9; i++)
            {
                if (e.Column.FieldName == $"Step{i}")
                {
                    var value = view.GetRowCellValue(e.RowHandle, e.Column);
                    if (value != null && int.TryParse(value.ToString(), out int stepVal))
                    {
                        switch (stepVal)
                        {
                            case 1:
                                e.Appearance.BackColor = Color.FromArgb(146, 208, 80);
                                break;
                            case 2:
                                e.Appearance.BackColor = Color.FromArgb(0, 176, 240);
                                break;
                            case 3:
                                e.Appearance.BackColor = Color.Red;
                                break;
                            case 4:
                                e.Appearance.BackColor = Color.FromArgb(234, 234, 234);
                                break;
                        }
                    }
                }
            }

        }//单元格根据状态变颜色
        private void GridView1_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
        {
            for (int i = 1; i <= 9; i++)
            {
                if (e.Column.FieldName == $"Step{i}")
                {
                    e.DisplayText = ""; // 不显示原始数字
                }
            }
        }//单元格根据状态变颜色
        private void SetColumnWidths(GridView view)
        {
            // 设置每个列的宽度
            SetColumnWidth(view, "A3ReportNumber", 150); // 设置 A3ReportNumber 列宽为 150
            SetColumnWidth(view, "A3ProblemStatement", 920); // 设置 A3ProblemStatement 列宽为 920
            SetColumnWidth(view, "Responsible", 150); // 设置 Responsible 列宽为 150

            // 设置 Step1 到 Step9 列宽为 70
            for (int i = 1; i <= 9; i++)
            {
                string colName = $"Step{i}";
                SetColumnWidth(view, colName, 70); // 设置 Step1 到 Step9 列宽为 70
            }
        }//设置列宽

        private void SetColumnWidth(GridView view, string columnName, int width)
        {
            // 获取列并设置宽度
            GridColumn column = view.Columns.ColumnByFieldName(columnName);
            if (column != null)
            {
                column.Width = width; // 设置列宽
            }
        }//设置列宽

        private void AddVisible()//修饰表格
        {
            //加载需要的列，并且修改显示名称
            A3list.Columns.AddVisible("A3ReportNumber", "A3 Report Number");
            A3list.Columns.AddVisible("A3ProblemStatement", "A3 Problem Statement");
            A3list.Columns.AddVisible("Responsible", "Responsible");
            A3list.Columns.AddVisible("Step1", "Step 1");
            A3list.Columns.AddVisible("Step2", "Step 2");
            A3list.Columns.AddVisible("Step3", "Step 3");
            A3list.Columns.AddVisible("Step4", "Step 4");
            A3list.Columns.AddVisible("Step5", "Step 5");
            A3list.Columns.AddVisible("Step6", "Step 6");
            A3list.Columns.AddVisible("Step7", "Step 7");
            A3list.Columns.AddVisible("Step8", "Step 8");
            A3list.Columns.AddVisible("Step9", "Step 9");
            //设置文本列不可编辑
            A3list.Columns["A3ReportNumber"].OptionsColumn.AllowEdit = false;
            A3list.Columns["A3ProblemStatement"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Responsible"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step1"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step2"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step3"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step4"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step5"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step6"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step7"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step8"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step9"].OptionsColumn.AllowEdit = false;
            //单元格根据状态变颜色
            GridView gridView1 = A3.MainView as GridView;
            if (gridView1 != null)
            {
                gridView1.RowCellStyle += GridView1_RowCellStyle;
                gridView1.CustomColumnDisplayText += GridView1_CustomColumnDisplayText;
            }
            // 禁用自动列宽，以便手动设置
            gridView1.OptionsView.ColumnAutoWidth = false;

            // 自定义设置每个列的宽度
            SetColumnWidths(gridView1);

        }
        private void lbRCActive_Click(object sender, EventArgs e)
        {
            //点击Active显示下方绿条
            plRCActive.BackColor = Color.FromArgb(146, 208, 80);
            plRCOverdue.BackColor = Color.Transparent;
            plRCTotal.BackColor = Color.Transparent;
            //加载表格

            DataTable dt = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"FactoryID = {SystemInfo.readFactory}  and DepartmentID = {SystemInfo.readparentDep} and A3Status = 1");
            A3.DataSource = dt;
            A3list.OptionsView.ShowIndicator = false;
            A3list.Columns.Clear();
            AddVisible();
            lbRCActive.Text = dt.Rows.Count.ToString();

        }

        private void lbRCOverdue_Click(object sender, EventArgs e)
        {
            //点击Overdue显示下方绿条
            plRCActive.BackColor = Color.Transparent;
            plRCOverdue.BackColor = Color.FromArgb(146, 208, 80);
            plRCTotal.BackColor = Color.Transparent;

            //加载表格
            DataTable dt = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"FactoryID = {SystemInfo.readFactory}  and DepartmentID = {SystemInfo.readparentDep} and A3Status = 1");
            List<int> idList = new List<int>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                idList.Add(Convert.ToInt32(dt.Rows[i]["ID"]));
            }
            if (idList.Count > 0)
            {
                string idListString = string.Join(",", idList);
                DataTable dt2 = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_Step1", $"A3ReportNumberID IN({idListString}) and Duedate < '{DateTime.Now}'");
                List<int> idList2 = new List<int>();
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    idList2.Add(Convert.ToInt32(dt2.Rows[i]["A3ReportNumberID"]));

                }
                if (idList2.Count > 0)
                {
                    string idListString2 = string.Join(",", idList2);
                    DataTable dt3 = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"ID IN({idListString2})");
                    // 绑定到 GridControl
                    A3.DataSource = dt3;
                    lbRCOverdue.Text = dt3.Rows.Count.ToString();

                }
                else
                {
                    lbRCOverdue.Text = "0";
                    lbRCOverdue.Appearance.ForeColor = Color.Silver;
                }

            }
            else
            {
                lbRCOverdue.Text = "0";
                lbRCOverdue.Appearance.ForeColor = Color.Silver;
            }
            A3list.OptionsView.ShowIndicator = false;//取消显示行号
            A3list.Columns.Clear();
            AddVisible();

        }

        private void lbRCTotal_Click(object sender, EventArgs e)
        {
            //点击Total显示下方绿条
            plRCActive.BackColor = Color.Transparent;
            plRCOverdue.BackColor = Color.Transparent;
            plRCTotal.BackColor = Color.FromArgb(146, 208, 80);
            //加载表格
            DataTable dt = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"FactoryID = {SystemInfo.readFactory}  and DepartmentID = {SystemInfo.readparentDep} ");
            A3.DataSource = dt;
            A3list.OptionsView.ShowIndicator = false;
            A3list.Columns.Clear();
            AddVisible();
            lbRCTotal.Text = dt.Rows.Count.ToString();

        }

        private void A3list_DoubleClick(object sender, EventArgs e)
        {
            int selectedRowHandle = A3list.FocusedRowHandle;

            if (selectedRowHandle >= 0)
            {
                object selectedValue = A3list.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null && selectedValue != DBNull.Value)
                {
                    A3number = selectedValue.ToString();
                    Step1 frm = new Step1();
                    frm.Show();
                }
                else
                {
                    MessageBox.Show("选中记录的 ID 为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void btnA3Edit_Click(object sender, EventArgs e)
        {
            // 获取选中行的索引
            int selectedRowHandle = A3list.FocusedRowHandle;

            if (selectedRowHandle >= 0) // 确保有选中行
            {
                // 假设你要保存的列名是 "ColumnName"，请替换为你的实际列名
                object selectedValue = A3list.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null)
                {
                    A3number = selectedValue.ToString();
                    Step1 frm = new Step1();
                    frm.Show();

                }
                else
                {
                    MessageBox.Show("选中的列数据为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请先选择一条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnA3Delete_Click(object sender, EventArgs e)
        {
            // 获取选中行的索引
            int selectedRowHandle = A3list.FocusedRowHandle;

            if (selectedRowHandle >= 0) // 确保有选中行
            {
                // 假设你要保存的列名是 "ColumnName"，请替换为你的实际列名
                object selectedValue = A3list.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null)
                {
                    // 弹出确认对话框，询问是否继续操作
                    DialogResult result = MessageBox.Show("是否删除选中的A3?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    // 判断用户点击了“是”按钮
                    if (result == DialogResult.Yes)
                    {
                        int ID = Convert.ToInt32(selectedValue);
                        // 执行操作
                        bool reslist = LSQL.SQL.Update(SystemInfo.SQL, "A3_List", "Del_tag = 1", $"ID = '{ID}'");
                        if (reslist)
                        {
                            MessageBox.Show("已删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        }
                    }
                    else
                    {
                        // 用户点击了“否”，可以进行相应的处理，或者什么也不做
                        MessageBox.Show("操作已取消", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                else
                {
                    MessageBox.Show("选中的列数据为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请先选择一条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region CIP

        #endregion

        private void btnCascade_Click(object sender, EventArgs e)
        {
            cascadeForm.instance.ShowDialog();
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            Form1.instance = new Form1();
            Form1.instance.Show();
        }

        private void linkCalendar_Click(object sender, EventArgs e)
        {
            mainTab.SelectedTabPageIndex = 11;
            Key_Calendar.keyCalendar.FormBorderStyle = FormBorderStyle.None;
            Key_Calendar.keyCalendar.TopLevel = false;
            plKeyCalendar.Controls.Add(Key_Calendar.keyCalendar);
            Key_Calendar.keyCalendar.Show();
        }

        private void btnMessage_Click(object sender, EventArgs e)
        {
            //MessageBox.Show($"readFactory = {SystemInfo.readFactory}\nreadLevel = {SystemInfo.readLevel}\nreadParent = {SystemInfo.readparentDep}\nreadDepartment = {SystemInfo.readDepartment}\nfac = {Properties.Settings.Default.Factory}");
            messageForm.instance.ShowDialog();

            DataTable dt = publicFunc.UserIncompleteAction(SystemInfo.userID);
            badge.Properties.Text = dt.Rows.Count.ToString();

        }

        private async void btnScore_Click(object sender, EventArgs e)
        {
            if (rowIndex == -1)
            {
                MessageBox.Show("未选中Topic，请选择");
                return;
            }
            string assign = gvDeviation.GetRowCellValue(rowIndex, "提出部门").ToString();
            string resDep = gvDeviation.GetRowCellValue(rowIndex, "负责部门").ToString();
            string resPerson = gvDeviation.GetRowCellValue(rowIndex, "负责人姓名").ToString();
            string dueon = gvDeviation.GetRowCellValue(rowIndex, "DueDate").ToString();
            string topic = gvDeviation.GetRowCellValue(rowIndex, "TopicINFO").ToString();
            string root = gvDeviation.GetRowCellValue(rowIndex, "RootCause").ToString();
            string todo = gvDeviation.GetRowCellValue(rowIndex, "TodoINFO").ToString();

            string conent = $"提出部门: {assign}\nTopic: {topic}\nRoot cause: {root}\nTo do/Action: {todo}\n负责部门: {resDep},负责人: {resPerson}";

            string prompt = @"你是一个评分员，根据用户回答的完整性、清晰度、可行性三个维度自动评分，并提供优化建议。总评分为10分，具体评分细则如下：

1. 问题描述 (本大项满分2分)
评分维度
清晰性（0.8分）：是否准确描述问题现象/现象 (原4分占比，即4/10 * 2分)
数据支持（0.6分）：是否有日志/截图/数据佐证 (原3分占比，即3/10 * 2分)
复现路径（0.6分）：是否说明触发条件或复现步骤 (原3分占比，即3/10 * 2分)

2. 有何影响 (本大项满分2分)
评分维度
影响范围（0.8分）：明确受影响用户/系统模块 (原4分占比)
严重程度（0.6分）：定性说明（如阻塞/次要） (原3分占比)
时效性（0.6分）：是否标注紧急程度（如P0-P3） (原3分占比)

3. 应对措施 (本大项满分2分)
评分维度
可行性（0.8分）：方案是否可快速执行 (原4分占比)
成本评估（0.6分）：是否考虑资源/时间消耗 (原3分占比)
备选方案（0.6分）：是否有Plan B (原3分占比)

4. 下一步计划 (本大项满分2分)
评分维度
责任人（0.6分）：是否指定负责人 (原3分占比)
时间节点（0.8分）：是否有明确截止时间 (原4分占比)
里程碑（0.6分）：是否拆分阶段任务 (原3分占比)

5. 需要如何支持 (本大项满分2分)
评分维度
资源需求（0.8分）：是否列明具体需求（人力/预算） (原4分占比)
协作方（0.6分）：是否标注依赖部门/成员 (原3分占比)
优先级（0.6分）：是否说明支持紧急度 (原3分占比)

重要：请严格按照以下要求输出结果：
1. 绝对不要使用任何HTML标签（如<h3>、<strong>、<style>等）
2. 不要使用Markdown格式（如**、###等）
3. 不要使用任何样式或格式标记
4. 使用纯文本格式，用换行和缩进来组织内容
5. 仅输出：总分、各维度得分、优化建议
6. 输出格式示例：
总分：X.X/10
各维度得分：
1. 问题描述：X.X/2.0
2. 有何影响：X.X/2.0
...
优化建议：
1. ...
2. ...
";

            string prompt_en = @"You are a grader. Based on the user’s answer, evaluate across three dimensions: completeness, clarity, and feasibility. The total score is 10 points. Scoring rules are as follows:  

1. Problem Description (2.0 points)  
   - Clarity (0.8): Is the problem phenomenon accurately described?  
   - Data Support (0.6): Are there logs/screenshots/data as evidence?  
   - Reproduction Path (0.6): Are triggering conditions or reproduction steps provided?  

2. Impact (2.0 points)  
   - Impact Range (0.8): Does it specify which users/modules are affected?  
   - Severity (0.6): Is there a qualitative description (blocking/minor)?  
   - Timeliness (0.6): Is urgency level stated (e.g., P0-P3)?  

3. Countermeasures (2.0 points)  
   - Feasibility (0.8): Can the proposed plan be quickly executed?  
   - Cost Evaluation (0.6): Are resource/time costs considered?  
   - Alternative Plan (0.6): Is there a Plan B?  

4. Next Steps (2.0 points)  
   - Responsible Person (0.6): Is someone assigned?  
   - Timeline (0.8): Is there a clear deadline?  
   - Milestones (0.6): Are phased tasks defined?  

5. Required Support (2.0 points)  
   - Resource Needs (0.8): Are specific needs (staff/budget) listed?  
   - Collaborators (0.6): Are dependent departments/members specified?  
   - Priority (0.6): Is the urgency of support indicated?  

Important output rules:  
1. Do NOT use any HTML tags (like <h3>, <strong>, <style>, etc.)  
2. Do NOT use Markdown formatting (like **, ###, etc.)  
3. Do NOT use any styles or formatting markers  
4. Use only plain text with line breaks and indentation for structure  
5. Output only: total score, individual dimension scores, and optimization suggestions  
6. Output format example:  

Total Score: X.X/10  

Scores by Dimension:  
1. Problem Description: X.X/2.0  
2. Impact: X.X/2.0  
3. Countermeasures: X.X/2.0  
4. Next Steps: X.X/2.0  
5. Required Support: X.X/2.0  

Optimization Suggestions:  
1. …  
2. …  

Optimization Suggestions must be writen by English

";

            string response = await GetChatResponse(conent, prompt_en);

            //MessageBox.Show(response);
            scoreForm.scoreDetail = response;
            scoreForm.instance.ShowDialog();

        }

        private static readonly HttpClient client = new HttpClient();
        private async Task<string> GetChatResponse(string message, string prompt)
        {
            var requestBody = new
            {
                model = "deepseek-chat",
                messages = new[]
                {
                    new { role = "system", content = prompt },
                    new { role = "user", content = message }
                },
                stream = false
            };

            var requestJson = JsonConvert.SerializeObject(requestBody);
            var request = new HttpRequestMessage(HttpMethod.Post, "https://api.deepseek.com/chat/completions");
            string apiKey = "sk-5c7ec7a2a74945c5902ff20f896a8dab";
            request.Headers.Add("Authorization", $"Bearer {apiKey}");
            request.Content = new StringContent(requestJson, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();
                var responseBody = await response.Content.ReadAsStringAsync();
                dynamic result = JsonConvert.DeserializeObject(responseBody);
                string content = result.choices[0].message.content.ToString();

                // 清理HTML标签，转换为纯文本
                content = CleanHtmlTags(content);

                return content;
            }
            catch (Exception ex)
            {
                return "请求失败: " + ex.Message;
            }
        }
        private string CleanHtmlTags(string html)
        {
            if (string.IsNullOrEmpty(html))
                return html;

            // 移除<style>标签及其内容
            string result = System.Text.RegularExpressions.Regex.Replace(html, @"<style[^>]*>.*?</style>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);

            // 移除<script>标签及其内容
            result = System.Text.RegularExpressions.Regex.Replace(result, @"<script[^>]*>.*?</script>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);

            // 移除所有HTML标签
            result = System.Text.RegularExpressions.Regex.Replace(result, @"<[^>]+>", "");

            // 解码HTML实体
            result = System.Net.WebUtility.HtmlDecode(result);

            // 将HTML换行转换为普通换行
            result = result.Replace("<br>", "\n").Replace("<br/>", "\n").Replace("<br />", "\n");

            // 清理多余的空白字符，但保留换行
            result = System.Text.RegularExpressions.Regex.Replace(result, @"[ \t]+", " ");
            result = System.Text.RegularExpressions.Regex.Replace(result, @"\n\s*\n", "\n\n");

            // 移除首尾空白
            result = result.Trim();

            return result;
        }
        private void simpleButton3_Click(object sender, EventArgs e)
        {

        }

        private void simpleButton7_Click(object sender, EventArgs e)
        {
            // 获取当前选中行Status列的值
            object statusValue = gvDeviation.GetFocusedRowCellValue("Status");
            if (statusValue != null)
            {
                // 如果是ImageComboBoxItem的值，需要转换
                int selectedValue = Convert.ToInt32(statusValue);
                // selectedValue对应你设置的值：1=0%, 2=25%, 3=50%, 4=75%, 5=100%
                MessageBox.Show(selectedValue.ToString());
            }
           
        }

        
    }
}